Answer the question
In order to leave comments, you need to log in
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" => "КАКАЯ_ТО_ОШИБКА"
)
);
{
"status": "error",
"data": {
"message": "КАКАЯ_ТО_ОШИБКА"
}
}
$k = 1;
$array = array();
while ($row = $result->fetch_assoc()) {
$array[$k] = array(
"id" => $row['id'],
"name" => $row['name']
);
$k++;
}
{
"1": {
"id": "1",
"name": "1"
},
"2": {
"id": "2",
"name": "1"
}
}
function search() {
var data = {
search: $('#search').val()
}
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ajax/xxx.php',
data: data,
success: function(data) {
search_answer(data);
}
});
};
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");
}
}
};
Answer the question
In order to leave comments, you need to log in
Instead of dataType: 'text'
inserting dataType: 'json'
and in the body of the function success
is not necessaryJSON.parse()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question