O
O
Oleg Galimov2018-02-01 10:58:42
PHP
Oleg Galimov, 2018-02-01 10:58:42

How to send a single variable from Ajax and get an Ajax response as an array?

Good time of the day.
Tell me how to send one variable from Ajax, namely the domain name and get an Ajax response in the form of an array
that should generate a table.
I do so.

<form method="post">
<table>
  <tr><td>Domain:</td><td><input id="out_domain" type="text" name="domain" value="ufanalog.ru"></td></tr>
</table>
  <div class="button_records"><input type="submit" name="getRrRecords" value="Получить записи"></div>
</form>

php handler
<?
ini_set('display_errors',1);
include '../reg/soap_action_getrrrecords.php'; //Подключение по API к SOAP-сервер
if($_POST['domain'])
  {
      try	{
      //вызываем функцию получения списка RR записей подомену
      $getrrrecord = $client->getRrRecords($_POST['domain']);
        }
      catch (SoapFault $fault)
        {
          //Неудалось вызвать функциюget RrRecords на сервере или она отработала неправильно.
          echo '<div class="forma"><b>Невозможно выполнить функцию четения записи DNS</b></div>';
          //echo $format1."Couldntexecute getRrRecords".$format2;
          //echo "Fault code: ".$fault->faultcode."<br>Fault message: ".$fault->faultstring;
          logout();
          exit();
        }
      if ($getrrrecord->status->code != '1')
        {
          //функция отработала, возникла обработанная ошибка с идентификатором $getrrrecord->status->name,выдаем сообщение.
          echo '<div class="forma"><b>Не удалось получить записи DNS</b></div>';
          echo '<div class="error_messages"><form action="../index.php"><button class="button" type="submit">Главная</button></form></div>';
          //echo $format1."Failed to getRRrecords".$format2;
          //echo "Error name:".$getrrrecord->status->name."<br>Error message:".$getrrrecord->status->message;
          logout();
          exit();
        }
          else
        {
          foreach($getrrrecord->data=>$record)
          /*/Успешно получили список записей с SOAP-сервера.
          echo "<form><table class='info'><tr><td><h1>Существующие записи в доменном имени <span class='dell_name'>$namedomain.</span></h1></td></tr><tr><td><table class='info_2'><tr><td>N</td><td>ID</td><td class='owner'>Имя записи</td><td>Действие</td><td>Тип записи</td><td>Приоритет</td><td>Вес</td>
            <td>Порт</td><td>Значение</td><!--td>Алгоритм</td><td>Приведение типа</td><td>Комментарий</td--></tr>";
              foreach($getrrrecord->data as $key =>$record)
                {
                  echo"<tr><td>".($key+1)."</td>
                  <td class='id'>".$record->id."</td>
                  <td class='owner'>".$record->owner."</td>
                  <td><button title='Удалить' id='".$record->id."' class='delete_btn'><img src='../images/delete_2.png' alt='Удаление' style='vertical-align:middle'> Удалить</button></td>
                  <td class='type_record'>".$record->type_record."</td>
                  <td class='pri'>".$record->pri."</td>
                  <td class='weight'>".$record->weight."</td>
                  <td class='port'>".$record->port."</td>
                  <td class='td_value'>".$record->data."</td>
                  <!--td class='sshfp_algorithm'>".$record->sshfp_algorithm."</td>
                  <td class='sshfp_type'>".$record->sshfp_type."</td>
                  <td class='info_rec'>".$record->info."</td--></tr>";
                }
          echo '</table></td></tr></table></form>';
        }*/
      echo json_encode($record->id, $record->owner, $record->type_record, $record->pri, $record->weight, $record->port, $record->data);
  }
?>

ajax
$('.button_records').click(function(e){
    e.preventDefault();
    ajaxGetRrRecords();
  });
  function ajaxGetRrRecords(){
    var domain = $('#out_domain').val();
    /*var id = $record->id;
    var owner = $record->owner;
    var type_record = $record->type_record;
    var pri = $record->pri;
    var weight = $record->weight;
    var port = $record->port;
    var data = $record->data;*/
    $.ajax({
      type: "POST",
      cache: false,
      url: "getrerecords.php",
      data:{domain:domain},
      dataType: "json",
      success: function(data){
      console.log(data);
      }
    });
  }

I have an error Ajax does not find the php handler, where did I write it wrong?
Help me to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Rudkovsky, 2018-02-01
@AlexRudkowskij

See how to properly work with the json_encode function here . You are not using it correctly.
In addition, you write json in a loop. You won't be able to process it after that.
You need to do something like this:

$response = [];
foreach($getrrrecord->data=>$record) {
    array_push($response, [
        'id' => $record->id,
        'owner' => $record->owner,
        ....
    ])
}
echo json_encode($response);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question