9

i have this ajax code

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById('addIO').innerHTML+=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/3/TRUE",true);
xmlhttp.send();

and I have a php array

$cars=array("Saab","Volvo","BMW","Toyota");

how can i send the array $cars to my javascript ?

3

2 Answers 2

16

PHP

echo json_encode($cars);

JavaScript

Native:

var foo = JSON.parse(xmlhttp.responseText);

With jQuery:

var foo = $.parseJSON(xmlhttp.responseText);
//or
$.getJSON("url", function(data){
    //data is your array
});

UPDATE

if(xmlhttp.readyState==4 && xmlhttp.status==200){
     //document.getElementById('addIO').innerHTML+=xmlhttp.responseText;
    var cars = JSON.parse(xmlhttp.responseText);  //cars will now be the array.
     //Do whatever you want here.
    $("#addIO").html(cars.join(", "));     //Join array with ", " then put it in addIO
}

If you want to use jQuery, put this in <head>:

<script type="text/javascript" src="link/to/the/file/jquery.js"></script>
Sign up to request clarification or add additional context in comments.

9 Comments

It works, and if your browser does not support it, try jQuery.
do u mean that i have to do ur code instead of my fourth code in my function?
i don't know jQuery, so please would u tell me where should i put ur javascript line code in my function
i tried this on my function document.getElementById('addIO').innerHTML=foo[0]; but it doesn't echo anythink
@William: This has nothing to do with jQuery. xmlhttp.responseText contains the response of the request as you already know. Put the code there where you have access to xmlhttp.responseText. If you are new to Ajax, you might want to read developer.mozilla.org/en/AJAX/Getting_Started
|
5

Use JSON:

echo json_encode($cars);

3 Comments

@Itay Moav - JSON.parse() in JavaScript.
thank you for ur answer but how can i save the returned data on my javascript?
@Derek I am not the one who asked the question.

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.