1

I have created a JSON object in php using json_encode and am attempting to display certain values of that object in javascipt through AJAX. I have no issue receiving the response from php but am getting 'undefined' when I try to access any value of the response using JSON notation.

Code snippet:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
   var response = xmlhttp.responseText;
   alert(response);
   alert(response.data);
}

Output:

{"data":[{"cheese":"pork"},{"cheese":"chicken"}]} // Yes, I'm hungry right now.
undefined

EDIT: Thanks everybody for the responses. Wish I could give you all a check mark but I have selected the most helpful response.

1
  • 1
    You need to parse that JSON back into JavaScript objects see JSON2.js {or if you're desperate use eval, but there's security risks of this} Commented Jul 20, 2011 at 16:55

5 Answers 5

2

You have to parse the json. This can be done through a simple call to eval, but this can only be done if you absolutely trust the returning server as he can make your script execute everything.

 var data = eval('('+response+')');

The way I would recommand if to use json2.js, a small javascript library that ius faster and will handle the parsing for you.

var data = JSON.parse(response);

It can be acquire from https://github.com/douglascrockford/JSON-js

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

Comments

1

You need to parse the JSON:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
   var jdoc = JSON.parse(xmlhttp.responseText);
   alert(jdoc.data[0].cheese);
}

Include json2.js in older browsers.

1 Comment

Please tell me if there is an error in the code I'm writing. Thanks!
1

You have to convert response into js object.

The simpliest way is to use eval():

eval('var result = ' +response);
alert(result.data);

Comments

1
var response = xmlhttp.responseText

this is not a JSON object. This is plain text. Use var myObject = eval('(' + myJSONtext + ')'); for example to get JSON (eval is evil:)

Comments

1

Looks like response is plain text. Try this:

var response = xmlhttp.responseText;
var data = new Function("return "+xmlhttp.responseText)();

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.