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 ?

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/

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

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);
        });
    }
});

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
    }
    });

Comments

Your Answer

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.