JSON variable returning correct but value is undefined?
Here is my success function for my ajax request via jquery,
success: function(response) {
if (response.error == undefined) {
alert(response);开发者_运维知识库
}
$('#' + id).after('<div id="emailMsg" class="error">' + response.error + '</div>');
}
Because the value is coming back as undefined it alerts me the returned JSON which is...
{"error":true}
Why is this happening, surely when I call response.error I should get either true or false.
UPDATE
Variable is returning as a string and not boolean, my json_encode();
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array('error' => true));
}
You might want to try adding the dataType: 'json'
parameter to your $.ajax
call. That will ensure that jQuery will take care of making the response an object for you.
You need to first parse the JSON from a string into a JavaScript object.
This can be done with JSON.parse(response)
. In old browsers that don't have native JSON, eval(response)
works too, but is less secure.
精彩评论