0

I send an array from PHP with json_encode, and I trying to get with AJAX and jQuery. Every thing is ok.

JSON structure is :

names{"p1":"John","p5":"Smith"}

jQuery code is :

$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
 $(data.names).each(function(key, txt) {
 alert(txt);
 });
 }
}

this code don't return any thing! I think browser don't enter in each

what should I do ?

asked Dec 16, 2012 at 17:34

3 Answers 3

3

instead this:

$(data.names).each(function(key, txt) {
 alert(txt);
});

use this:

$.each(data.names, function(key, txt) {
 alert(txt);
});

and your json seems to be incorrect as you mentioned: names{"p1":"John","p5":"Smith"}

this should be like this:

{
 "names": {
 "p1": "John",
 "p5": "Smith"
 }
}

you can check your json here: http://jsonlint.com/

answered Dec 16, 2012 at 17:36

Comments

1

I'd suggest you use jQuery's $.getJSON(); http://api.jquery.com/jQuery.getJSON/ But to answer your question directly; you didn't close your ajax() function.

$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
 $(data.names).each(function(key, txt) {
 alert(txt);
 });
 }
});
answered Dec 16, 2012 at 17:38

Comments

1

In your code you could just use parseJSON().

 $.ajax({
 type: "POST",
 url: "return.php",
 dataType: "json",
 data: "id=56",
 success: function(data) {
 var d = jQuery.parseJSON(data); 
 // ... do stuff
 }
 });
answered Dec 16, 2012 at 18:15

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.