0

I have this ajax request:

var rootURL = "http://localhost/myapp/api/api.php"; $.ajax({ type: 'GET', url: rootURL + '/favourites', dataType: "json", success: function(list) { }, error: function(list) { } }); 

and the api.php makes a query to DB and the encoded result

echo '{"result": ' . json_encode($result) . '}'; 

is like this:

{ "result": [ { "ID": "1", "username": "username1", "name": "name1", "year": "year1" }, { "ID": "2", "username": "username2", "name": "name2", "year": "year2" } ] } 

Now how can I get and print the two rows of the JSON result list in success callback in Javascript? I tried this:

var decoded = JSON.parse( lista ); 

but I receive an error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Thanks

1
  • put the results into an attribute result ? Why not echo json_encode($result); Commented Jun 3, 2014 at 10:21

2 Answers 2

4

You dont't need to parse, just you need to iterate the array inside the result.

do like this:

success: function(list) { $.each(list.result,function(index,item){ console.log(item); }); } 

FIDDLE DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

@BastienSander No! Here one have to loop in it because result holds an array which contains some js objects in it.
There only one instance of list.result, so I don't get the reason of $.each
What will you do to take something from list.result. $.each is for iterating through each item in list.result
2

Don't call JSON.parse. jQuery does that for you when you say dataType: "json". list is an object. So just access list.result, which contains the result array.

Also, your PHP shouldn't build the JSON by hand like that. It should do:

echo json_encode(array('result' => $result)); 

1 Comment

thanks, very helpful to remind me I forgot: "jQuery does that for you when you say dataType: 'json'". :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.