S
S
slowpoke592018-07-19 10:59:26
JavaScript
slowpoke59, 2018-07-19 10:59:26

How to parse JSON to JS/JQ?

Good afternoon!

Straight to the point:
There is a certain search field, when you enter something into it, an ajax request is sent to the /ajax/xxx.php page.
It, in turn, sends json through json_encode, the answer may be different, if there is some kind of error:

Code php:

$status = 'error';
$array = array(
  "status" => $status,
  "data" => array(
    "message" => "КАКАЯ_ТО_ОШИБКА"
  )
);


Received json:
{
    "status": "error",
    "data": {
        "message": "КАКАЯ_ТО_ОШИБКА"
    }
}


And if there is a match in the database then:

PHP code:
$k = 1;
$array = array();
while ($row = $result->fetch_assoc()) {
  $array[$k] = array(
    "id" => $row['id'],
    "name" => $row['name']
  );
  $k++;
}


Received json:
{
    "1": {
        "id": "1",
        "name": "1"
    },
    "2": {
        "id": "2",
        "name": "1"
    }
}


Here is the ajax request itself:
function search() {
var data = {
  search: $('#search').val()
}
$.ajax({
  type: 'POST',
  dataType: 'json',
  url: '/ajax/xxx.php',
  data: data,
  success: function(data) {
    search_answer(data);
  }
});
};


And here is the function that "parses" the response:
function search_answer(res) {
// вывод найденной информации
if (res.status == 'error') {
  if (res.data.message == 'ERROR_2') {
    $(".error").text("ERROR_2");
  }
  if (res.data.message == 'ERROR_1') {
    $(".error").text("ERROR_1");
  }
}
};


I understand that it’s a fierce code, but I ask for help, I just can’t figure out how to display the results.

UPD. If you got id and name, then you need to display them in a div with the answer class. As I understand it, a loop is needed to iterate through the resulting array, but I can’t figure out how to compose it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ihor Bratukh, 2018-07-19
@BRAGA96

Instead of dataType: 'text'inserting dataType: 'json'and in the body of the function successis not necessaryJSON.parse()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question