1

I am trying to return a php associative array to javascript array through ajaxRequest.responseText

Here's what I do.

First in php, I do this:

$encoded = json_encode($thisarray);
echo $encoded; 

If I echo $encoded, I get {"a":"apple,arrow","b":"boy,bank","c":"cat,camp"}

Then in js script,

thisarray = new Array();
thisarray = ajaxRequest.responseText;

If I alert thisarray, I get {"a":"apple,arrow","b":"boy,bank","c":"cat,camp"}

That's wrong since alerting an array should give error. But in this case, when I alert thisarray, I get the full array!!

Needless to say, I can't call my value out of thisarray, since it is yet defined as an array.

Anyone can tell me what am I missing here?

1 Answer 1

3

You need to parse the JSON string in JavaScript to get an object, preferably with the native JSON object of your browser, if available:

var thisarray = JSON.parse(ajaxRequest.responseText);

Otherwise you can use the JSON parser from JSON.org or jQuery.parseJSON if you’re already using jQuery.

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

6 Comments

Thanks! Em... native JSON object.... that brings another concern. Is JSON.parse cross browser?
Looks like it only support the latest versions. Is there other solutions that can be used for low-end browsers?
@Eric Sim: The native implementations of JSON.parse are based on the original parser written by Douglas Crockford. If you use his script, json.org/json2.js, it will create the global JSON object and its methods for you if they aren't already available.
It's possible (though not recommended) to use javascript's EVAL() to 'convert' a JSON string to an array: var thisarray = eval(ajaxRequest.responseText)
|

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.