I am banging my head against the wall here, and I am hoping someone can help me out.
I have an AJAX function which calls a PHP page. That page returns a JSON object, which should then be parsed and displayed to the user. Everything works fine except when the JSON object is returned, trying to parse it gives undefined.
The PHP:
$jsonArray= array(
'request' => 'this is the request',
'response' => 'this is the response'
);
echo json_encode($jsonArray);
On the Ajax side, I do the following:
var display=xmlHttp.responseText;
alert(display); //gives {"request":"this is the request","response":"This is the response"}
alert(display.request); //gives undefined
Am I missing something obvious? Pasting the same string directly into a JavaScript variable seems to work fine...
4 Answers 4
You will need to parse the json string. JSON.parse should do the tricks. If it's not working, there's probably a problème with the object you encoded.
Comments
You need to parse the JSON data returned from your server. There are many libraries to do this such as:
1 Comment
$.parseJSON: api.jquery.com/jQuery.parseJSON var myObject = eval('(' + display + ')');
Comments
display is a string. you will need to use
var obj = eval(display)
but eval() is not as safe as using JSON.parse().
application/json. You can use the PHP codeheader('Content-type: application/json');before the echo statement to set this.