How can I return an array from php in javascript using ajax

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 $ cars array to my javascript?

+8
javascript ajax php
source share
2 answers

Php

 echo json_encode($cars); 

Javascript

Native

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

Using 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> 
+14
source share

Use JSON :

 echo json_encode($cars); 
+5
source share

All Articles