MajAfy
MajAfy

Reputation: 3097

read JSON data from PHP with jQuery

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

Answers (3)

Nifhel
Nifhel

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

Jai
Jai

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

Bart Verhaegh
Bart Verhaegh

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

Related Questions