0

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

3
  • 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. Commented Nov 6, 2010 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. Commented Nov 6, 2010 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. Commented Nov 6, 2010 at 16:50

4 Answers 4

2

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.

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

Comments

1

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

jQuery,

1 Comment

Documentation for jQuery's $.parseJSON: api.jquery.com/jQuery.parseJSON
1
var myObject = eval('(' + display + ')');

Comments

0

display is a string. you will need to use

var obj = eval(display)

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

2 Comments

Please validate before parsing script from an external source. This is a leading cause in cross-site scripting (XSS).
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.

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.