Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I return array from php to 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 the array $cars to my javascript ?

like image 326
William Kinaan Avatar asked May 06 '12 21:05

William Kinaan


People also ask

Can you pass PHP array to JavaScript?

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function. PHP array can be converted to JavScript array and accessible in JavaScript. Whatever the array type is, a single or multidimensional or indexed or associative array.

Can we send array through AJAX?

You can simply pass a JavaScript Array variable in the $. ajax as any other variable. On PHP script you can directly use it as a normal PHP Array.

Can AJAX be used with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.

What can AJAX return?

ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.


1 Answers

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>
like image 156
Derek 朕會功夫 Avatar answered Sep 23 '22 07:09

Derek 朕會功夫