Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  73] [ 2]  / answers: 1 / hits: 20963  / 12 Years ago, sun, may 6, 2012, 12:00:00

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 ?


More From » php

 Answers
75

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>

[#85749] Saturday, May 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hallie

Total Points: 503
Total Questions: 114
Total Answers: 103

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;