1

Using the following jQuery, how can I read through the values of the JSON that's returned? With it how it is, the jQuery doesn't even run as there is an error in: alert("A" + obj.sender[0]);

var session_id = $(this).find(".session_id").val();
    $.ajax({
        type: 'POST',
        url: '../php/read.php',
        dataType: "json",
        data: {sesh_id: session_id},
        success: function (response) {
            var obj = jQuery.parseJSON(response);
            alert("A" + obj.sender[0]);
        },
        error: function (response) {
            alert("Err: " + response.status);
        }
    });

The value of response is:

[{
    "sender":"[email protected]",
    "details":"details1",
    "date":"2017-01-04 16:11:04"
},
{
    "sender":"[email protected]",
    "details":"details2",
    "date":"2017-01-04 16:11:05"
},
{
    "sender":"[email protected]",
    "details":"details3",
    "date":"2017-01-04 16:11:06"
}]
5
  • 4
    What is the error you get back? Commented Dec 7, 2016 at 15:48
  • does the URL its posting to actually exist? Commented Dec 7, 2016 at 15:50
  • check in inspector if you are getting the answer via javascript and what status code it has... my two guesses: 1. url is not valid in ajax request 2. somehow php returns HTTP 500 Commented Dec 7, 2016 at 15:56
  • You don't need var obj = jQuery.parseJSON(response);. Btw, you still need to add the actual error messages! Commented Dec 7, 2016 at 16:27
  • @RoryMcCrossan Updated question, previous question was wrong. Commented Dec 7, 2016 at 16:28

1 Answer 1

1

The issue you have is that your index accessor is in the wrong place as obj is an array, not the sender property, so it should be obj[0].sender.

You also don't need to call JSON.parse() on the response, as jQuery does that for you automatically as you specified dataType: 'json'. Try this:

$.ajax({
    type: 'POST',
    url: '../php/read.php',
    dataType: "json",
    data: { sesh_id: session_id },
    success: function (response) {
        console.log("A" + obj[0].sender);
    },
    error: function (response) {
        console.log("Err: " + response.status);
    }
});

Finally, note that console.log() is much more preferable when debugging over alert() as it doesn't coerce data types.

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

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.