s develop s develop - 1 month ago 5
Ajax Question

"Cannot use 'in' operator.." while fetching JSON string response in AJAX jQuery

I'm trying to create a JSON array in laravel and then trying to fetch it through ajax jquery. It does create JSON but while fetching it from jquery is creating problems. I'm no able to fetch key-value pair there.

Here's the code to create JSON array in Laravel (PHP):

foreach ($userIds as &$userId) {
$data[] = json_encode(array("Id"=>$id,"Name"=>$name,"HashId"=>$hashId));
}
return $data;


PS.
$data
shows this kind of response:

[
"{"Id":"111","Name":"abc","HashId":"I1J6EDO"}",
"{"Id":"112","Name":"xyz","HashId":"MDLYW9K"}"
]


this is how I'm trying to call ajax req:

$.ajax({
type: 'GET',
url: '/url/goes/here',
dataType: "json",
success: function(data) {
$.each(data, function(key, value){
$.each(value, function(key1, value1){
console.log(value1);
});
});
}
});


the console shows error:
Uncaught TypeError: Cannot use 'in' operator to search for..


after some search, I understood that maybe the response is string JSON array and not JSON array or obj (as expected)

I need help to fetch key-value pair. I'm also open to change the way I encode JSON in laravel. Kindly help as I'm new to both JSON and AJAX

Answer

You should encode everything after the arrays are built

$data = array();

foreach ($userIds as $userId) {
    $data[] = array("Id"=>$id,"Name"=>$name,"HashId"=>$hashId);
}
return json_encode($data);
Comments