0

My Javascript alert's undefined when trying to read the following JSON string:

[
    {
        "number_messages":"3"
    },
    {
        "message1":"abc"
    },
    {
        "message2":"c"
    },
    {
        "message3":"a"
    }
]

I am using AJAX to get this string (it gets trough correctly.

resp=jQuery.parseJSON(response);
alert( resp.number_messages );

My ajax call is:

$.ajax({  
type: 'POST',  
url: 'backend2.php',  
data: dataString,
success: submitFinished,
dataType: 'json'
});  

This alerts "undefined", no errors show up in dragonfly (it's like firebug but for opera).

I am quite new to the whole JSON JQuery thing, so it's prob. something really easy, but I can't seem to figure it out. I've searched for answers and edited my code for over an hour, and still haven't got it to work.

2
  • Where's response coming from? Chances are it doesn't contain the JSON string, but a response object. Commented Dec 9, 2011 at 22:43
  • stackoverflow.com/questions/5791356/… Commented Dec 9, 2011 at 22:46

2 Answers 2

3

Try this:

alert( resp[0].number_messages );
Sign up to request clarification or add additional context in comments.

2 Comments

You do see why that worked, right? It's because you have an array of structures (so you'll have to address each of the other elements with the appropriate index).
Yes, it's all clear now. Had been trying with .each because I figured it might be an array but didn't get it to work.
0

jQuery automatically parses json data into an object, you dont need jQuery.parseJSON(response)

$.ajax({
  "url":"page.php",
  "dataType":"json",
  "success":function(data){
    alert(data[0].number_messages);
  }
});

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.