22

I have used ajax in the code which works perfectly and give me json or array which ever I want as an output. the code I have used is,

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://map_ajax_control.php",false);
xmlhttp.send();

var test = xmlhttp.responseText;
alert(test);

This test variable gives me json/array.

I want to get the data which I received in the test variable in the JavaScript array.

The question is, how can I decode json data in javascript array? I have used the code as,

var output = new Array();  
output = json_decode(xmlhttp.responseText);

but this code is not giving me any output.
How can I do this two things?

1
  • 2
    Weighing down a web app with the entire jQuery library would be overkill if all this requires is logic for a json ajax handler Commented Sep 13, 2014 at 12:13

3 Answers 3

33

Most browsers support JSON.parse(). Its usage is simple:


obj = JSON.parse(xmlhttp.responseText);
alert(obj.length);

For the browsers that don't you can implement it using json2.js.

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

1 Comment

i have used this also.But its not working.It is not giving me any output
17

Try this:

var arr = xmlhttp.responseText.Split(',');

If it does not solve your problem then in your php code, use simple json_encode(your array); and on javascript, use myData= eval("(" + xmlHttp.responseText + ")"); .

I suggest you to follow this approach:

Encode the data you want to send by using a PHP binding for JSON at the server and decode the same using Javascript library for JSON. as:

var myObject = eval('(' + myJSONtext + ')');

or

var myObject = JSON.parse(myJSONtext, reviver);

Note: Include json2 javascript file to your solution..

Problem with storing values in Array from php to AJAX

2 Comments

Absolutely! I was getting a responseText object instead of a simple type. Using this approach ( and knowing a little about the object), I can extract the field d which is the boolean I cared about in this case.
WTH, PLEASE do not use the eval option of decoding the json, it is a blatant xss vulnerability
2

json is nothing but javascript object notation. You just need to parse it as suggested by Sudhir. You can also use jQuery.parseJSON for it.

And to do ajax, I strongly suggest you to use some library, preferably jQuery.

http://api.jquery.com/jQuery.ajax/

Comments

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.