1

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.

3
  • Without ajax how could you get the result from server using javascript ? May be I didn't get your question. Commented Jul 6, 2012 at 6:58
  • I didn't post the entire codes, but I did send ajax to the server, create my php array and send back to my JS. My problem is having strange output. Commented Jul 6, 2012 at 7:00
  • You should JSON.parse() the response you get in xmlhttp.responseText, it will not magically decode JSON by itself as jQuery does. Commented Jul 6, 2012 at 7:03

2 Answers 2

3

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!

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

Comments

2

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

1 Comment

Be aware of older browsers, specially ie < 8.

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.