1

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

asked Dec 17, 2013 at 13:49
1
  • you have to use data = JSON.parse(data); Commented Dec 17, 2013 at 13:50

2 Answers 2

1

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
 });
answered Dec 17, 2013 at 13:56

3 Comments

1. one should not use POST to retrieve data; 2. jQuery is smart enough to recognize JSON if headers are properly set, so no need to parse.
1. Agree. 2. I would say it's good practice to use JSON.parse
Nice but for some reason that was like have the solution I had to parse as you said then like a second layer of parsing 1- var obj = jQuery.parseJSON(data); 2- val = jQuery.parseJSON(obj);
1

Try the following...

$.each(data, function(key, value){
 var obj = JSON.parse(value);
 $.each(obj, function(key2, value2){
 console.log(key2 + ' - ' + value2);
 });
});
answered Dec 17, 2013 at 13:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.