I am trying to retrieve array that was created by php and send back to my JS script via ajax.
I am not sure how to display the value.
server side php
$r=array();
$r[] = 'aaa';
$r[] = 'bbb';
$r[] = 'ccc';
echo json_encode($r);
my JS
....ajax codes....
var p=document.getElementById('text');
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var r=xmlhttp.responseText;
for (var i=0; i<r.length; i++){
p.innerHTML= r[i] + '<br>';
}
}
The output will be
a
a
a
b
b
b
c
c
c
//but I want these
aaa
bbb
bbb
I want to use javascript instead of $.ajax to complete this. Any ideas?? Thanks a lot.
2 Answers 2
The easiest way to transfer an array from the server to the client is to use JSON. The following can be used to echo the array in JSON:
echo(json_encode($array));
See here for more information.
Then on the client side you can use the following function to decode the JSON to produce the same array:
decodedjson = JSON.parse(ajax.response);
Don't forget to wrap the client side code in an ajax call.
Hope this helps!
Comments
You have to parse the json string before, e.g. with JSON.parse. Try (untested):
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var r=JSON.parse(xmlhttp.responseText);
for (var i=0; i<r.length; i++){
p.innerHTML= r[i] + '<br>';
}
=== UPDATE ===
If you have to support very old browsers (e.g. less or equal then IE7) you should use libraries like Crockfords JSON2parser or jQuery (a huge lib with much more features).
JSON.parse()the response you get inxmlhttp.responseText, it will not magically decode JSON by itself as jQuery does.