up vote 0 down vote favorite

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...

link|flag
don't forget to send the correct headers with your JSON object (text/json). text/html will work because both are text, but it's good practice to send the correct mime type. – zzzzBov Nov 6 at 3:31
@zzzzBov: No, according to RFC 4627, the correct JSON MIME type is application/json. You can use the PHP code header('Content-type: application/json'); before the echo statement to set this. – idealmachine Nov 6 at 6:25
@idealmachine apologies, i didn't look up the correct mime type. My point still stands that text/html will work because both are text. – zzzzBov Nov 6 at 16:50

3 Answers

up vote 1 down vote

You need to parse the JSON data returned from your server. There are many libraries to do this such as:

jQuery,

link|flag
Documentation for jQuery's $.parseJSON: api.jquery.com/jQuery.parseJSON – idealmachine Nov 6 at 6:31
up vote 1 down vote
var myObject = eval('(' + display + ')');
link|flag
up vote 0 down vote

display is a string. you will need to use

var obj = eval(display)

but eval() is not as safe as using JSON.parse().

link|flag
Please validate before parsing script from an external source. This is a leading cause in cross-site scripting (XSS). – zzzzBov Nov 6 at 3:32
The code won't work if an object is returned instead of an array. Parentheses are needed for JavaScript to disambiguate between a) object literal notation, and b) a block of statements. – idealmachine Nov 6 at 6:30

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.