Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert json/array from ajax responseText in to javascript array?

Tags:

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?

like image 291
Arpi Patel Avatar asked Jan 31 '12 05:01

Arpi Patel


People also ask

How do you convert JSON to an array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

How do I convert XHR response to JSON?

To support older browsers, the best solution is to use the JSON. parse() method to convert the string returned by responseText to a JSON object: const xhr = new XMLHttpRequest(); xhr. onload = () => { const data = JSON.

Does JSON parse work on arrays?

We used the JSON. parse method to parse a JSON array into its JavaScript equivalent. The only parameter we passed to the method is the JSON string that should be parsed. If you provide invalid JSON to the method, a SyntaxError exception is thrown.


2 Answers

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.

like image 178
Sudhir Bastakoti Avatar answered Sep 18 '22 15:09

Sudhir Bastakoti


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

like image 45
Niranjan Singh Avatar answered Sep 18 '22 15:09

Niranjan Singh