I have a 2d array in a PHP file called $array, with the columns id, msg and timestamp
A multidimensional array is then created, and output as a JSON from an AJAX call:
$ok = 1;
$error = null;
echo JSON_ENCODE(array('ok'=>$ok, 'err'=>$error, 'arr'=>$array));
I am trying to loop through the nested array called arr, this I cannot figure out, what I have tried:
$.each(data,function(i,index){
$('#msg_apnd').append(data[index].midt + data[index].msg);
});
This only loops through the data array, and therefore only the one row, when I need it to loop through the nested arr array, so i tried this:
$.each(data,function(i,index){
$.each(i,function(i2,index2){
$('#msg_apnd').append(arr[index].midt + arr[index].msg);
});
});
I'm a little stuck and haven't been able to find a suitable answer elsewhere. I need the jQuery code to loop through the nested arr array in the AJAX response.
2 Answers 2
You can target the .arr using a member operator because data is an object
$.each(data.arr,function(idx, val){
$('#msg_apnd').append(val.midt + val.msg);
});
Also $.each() callback receives the index of the current item as the first argument and the current item as the second argument
Comments
The success callback should be like below:
function (response) {
console.log(response.ok, response.err, response.arr);
$.each(response.arr, function(i, v){
$('#msg_apnd').append(v.midt + v.msg);
});
}
Comments
Explore related questions
See similar questions with these tags.