SemperFly
SemperFly

Reputation: 1583

Reading php-encoded JSON in Javascript

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.

Upvotes: 1

Views: 2611

Answers (5)

Alex L
Alex L

Reputation: 8449

Looks like response is plain text. Try this:

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

Upvotes: 1

marc
marc

Reputation: 6223

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

Upvotes: 2

Londeren
Londeren

Reputation: 3331

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:)

Upvotes: 1

Molecular Man
Molecular Man

Reputation: 22386

You have to convert response into js object.

The simpliest way is to use eval():

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

Upvotes: 1

phihag
phihag

Reputation: 287755

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.

Upvotes: 1

Related Questions