Reputation: 3085
So I am trying to get sent an array of json objects from php file to js.
The method that I am using seems to be working since I used console.log to print the object (array) I am getting and I got what I really sent in the following format
(
[0] => {"id":"1","name":"mmdftd","phone":"5785","year":"2013","app_status":"in_progress"}
[1] => {"id":"2","name":"shsoshsdo","phone":"58","year":"2013","app_status":"in_progress"}
)
However I am facing an issue reading this array
I tried different ways to access it as following
First Way: .each function
$(data).each(function() {
console.log("This| " + this);
console.log("ID| " + val.id);
console.log("Name| " + val.name);
console.log("Phone| " + val.phone);
console.log("Year| " + val.year);
console.log("APP Status| " + val.app_status);
}
However this results in the following error
Uncaught Error: Syntax error, unrecognized expression: Array
Second way: Using while loog I am looping using this condition
while(data[i] != null)
However this results in an infinite loop
Any recommendation on which is the best practice to access such array ? Thanks in advance
Upvotes: 1
Views: 92
Reputation: 8074
Try the following...
$.each(data, function(key, value){
var obj = JSON.parse(value);
$.each(obj, function(key2, value2){
console.log(key2 + ' - ' + value2);
});
});
Upvotes: 1
Reputation: 2419
On PHP:
$data = array(
[0] => array("id"=>"1","name"=>"mmdftd","phone"=>"5785","year"=>"2013","app_status"=>"in_progress"),
[1] => array("id"=>"2","name"=>"shsoshsdo","phone"=>"58","year"=>"2013","app_status"=>"in_progress")
)
echo json_encode($data);
On JavaScript:
Let's assume you got the data by an ajax request.
$.get('url-to-php-file.php', function(data) {
data = JSON.parse(data);
// Here you can do whatever you want with the data
});
Upvotes: 1