Andy Andy - 1 month ago 13
jQuery Question

json parse error - Uncaught TypeError: Cannot use 'in' operator to search for '1009'

I'm developing an application which does an Ajax call to a PHP script which returns

json_encode
data.

The data is being returned from PHP as expected. But when trying to parse it in jquery I'm getting a console error:


Uncaught TypeError: Cannot use 'in' operator to search for '1009'


followed by a copy of my data array.

An example of the json encoded data is here:

[
{"u_id":"21747","fname":"Andy","lname":"","email":"foo@bar.com"},
{"u_id":"3748","fname":"John","lname":"","email":"foo@baz.com"},
{"u_id":"451750","fname":"Peter","lname":"","email":"someone@else.com"},
]


The jquery I'm using is as follows. The desired output is for it to display a list of people's email addresses next to a tickbox:

$(function() {
$('#myModal').on('shown.bs.modal', function() {
$(".modal-body").html("Loading...");
$.ajax({
url: "<?= $router->pathFor('/admin/ajax/find-user'); ?>",
data: {
searchInput: $('#searchInput').val()
},
method: "POST",
}).done(function(data) {
//$(".modal-body").html(data);
$.parseJSON(data);
$.each(data, function(key, value){
$(".modal-body").html('<input type="checkbox" id="' + value.u_id + '">' + value.email + "<br>");
});
});
});
});


What's wrong with this, and what does the error mean (I can't see 1009 anywhere in my data, although not sure if that's what it actually means?)

Answer

You need to parse your JSON data first:

var parsedData = $.parseJSON(data);

But if your PHP script returns the JSON with the correct Content-Type, you don't need to do that. If you ensure that the PHP script sends Content-Type: application/json, jQuery will automatically parse it before giving it to you. So that's another way to fix the problem.