views:

48

answers:

2

I have a result set that when I use json_encode() in php, returns the following

[
{"id":"1","name:","value"},
{"id":"2","name:","value"},
{"id":"3","name:","value"},
{"id":"4","name:","value"}
]

I'm then using jQuery to try and loop through this:

$.each(data, function(index, itemData){
  alert(itemData.id);
}

The problem is it's only getting the first record (id: 1).

Am I doing something wrong?

+4  A: 

This works for me, corrected a few of your typos:

var test = [{"id":"1","name":"value"},{"id":"2","name":"value"}];

$.each(test, function(index, itemData){
  alert(itemData.id);
});
Mike Gleason jr Couturier
+1 - beat me to it...typo is the cause!
David Hoerster
I must be blind...where are the typos?
Topher Fangio
Hi, `"name:","value"` instead of `"name":"value"`
Mike Gleason jr Couturier
@Mike - Thanks for the info. However, doesn't that seem like a copy/paste error? `json_encode` shouldn't return invalid data...
Topher Fangio
Hi, I understand, but it's difficult to give a good answer if the description is wrong..
Mike Gleason jr Couturier
A: 

This is a basic exmaple on how to use the JSON response of a AJAX request:

$.getJSON("http://example.com",
 function(data){
   $.each(data.items, function(i,item){
     // do something
   });
});
Kau-Boy
That's not really answering the question. The JSON data had a typo in it - the `each` loop was fine.
David Hoerster
He might have a point though, I was about to type a similar answer. IIRC, using `$.get` instead of `$.getJSON` caused this problem for me a few weeks ago.
Topher Fangio