user3419304
user3419304

Reputation: 279

How to get two return variables from AJAX

I m sending array table id to get the table no of that table id from database. and i need to add all those table id default seats and return.

JAVA SCRIPT :

        function showUser(str)
        {

        if (str=="")
          {
          str="";
          document.getElementById("table_Merge_comb").value = ''; 
          return;
          } 
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {

            document.getElementById("table_Merge_comb").value = xmlhttp.responseText; 
            }
          }
        xmlhttp.open("GET","get_tableno.php?table_id="+str,true);
        xmlhttp.send();
        }

get_table_no.php

<?PHP 
include 'config.php';
static $total_default_seats =0;
    $item = $_GET['table_id'];              
    $table_id = explode(",",$item);             
    $table_count = count($table_id);            

    for($i=0 ; $i<$table_count; ++$i)             
    {
        $qry = mysql_query("SELECT * FROM table_info WHERE table_id = '$table_id[$i]'");
        $row = mysql_fetch_array($qry);
        $table_no[$i] = $row['table_no'];
        $total_default_seats += $row['default_seats'];
    }
    echo implode(",",$table_no);    
?>

in this code echo implode(",",$table_no); and i get it and store it in textbox by document.getElementById("table_Merge_comb").value = xmlhttp.responseText; now i need to get $total_default_seats this value too

Upvotes: 0

Views: 65

Answers (2)

Kryten
Kryten

Reputation: 15760

Create an array in PHP, then send it back to the browser with json_encode:

$returnValues = array(
    "value1" => "a string that I want to return",
    "value2" => array( "some", "other", "values" ),
);

echo json_encode($returnValues);

This will send the following back to the browser:

{"value1":"a string that I want to return","value2":["some","other","values"]}

In your AJAX success error handler you can then get the value:

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

console.log(x.value1);    // outputs "a string I want to return"

console.log(x.value2[0]);    // outputs "some"

Then you can do whatever you want with the values.

This method allows you to send back any structured data you like - multiple return values (as an array), arrays, objects, etc.

Upvotes: 2

developerwjk
developerwjk

Reputation: 8659

Separate the two values by comma, then use split in Javascript:

var returnVars = xmlhttp.responseText.split(",");
var var1 = returnVars[0];
var var2 = returnVars[1];

Upvotes: 0

Related Questions