codenoob
codenoob

Reputation: 539

Ajax - success return more than 1 variable

Consider the example below:

I do an Ajax call to a php script and get 1 result. PHP echos out the result like below;

 echo json_encode($result);

Then in Javascript, the following code will retrieve the result.

         dataType: "JSON",
         success:function(data){
           var result = data
        }

Now I'm 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",
success:function(data1,data2){
    var result1 = data1
    var result2 = data2
}

Is this possible? If so, how?

Upvotes: 2

Views: 1506

Answers (1)

Derick Alangi
Derick Alangi

Reputation: 1100

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
}

Upvotes: 5

Related Questions