Reputation: 3097
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 ?
Upvotes: 0
Views: 310
Reputation: 2032
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 } });
Upvotes: 1
Reputation: 74738
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/
Upvotes: 3
Reputation: 11
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);
});
}
});
Upvotes: 1