codenoob codenoob - 1 year ago 58
Javascript Question

Ajax - success return more than 1 variable

consider this example:

I do a ajax calls to a php script and get 1 result. the php echo out the result like below

echo json_encode($result);

then in javascript, the following code will retrive the result.

dataType: "JSON",
var result = data

Now I am trying to see if I can have php script echo out 2 result and have javascript be able to distinguish them with something like the code below

echo json_encode($result);
echo json_encode($result2);

dataType: "JSON",
var result1 = data1
var result2 = data2

Is this possible ?
if so, how

Answer Source

You can send an array of values on successful return of AJAX:

echo json_encode(array("data1"=> $data1, "data2"=>$data2));

and print like this:

success: function(data){
    var res1 = data.data1
    var res2 = data.data2