Smokey
Smokey

Reputation: 1897

Error in displaying multiple values returned by AJAX function in PHP

Page 1:

I have a drop down menu whose values are passed to an AJAX function on selecting a particular option. And the AJAX function does multiple functionality & produces multiple values in page2. And I want to display all those values at multiple locations in page1. And when I tried doing this, error occurred.

My Page 1:

<selectid="ddl" name="ddl" onchange="show_details(this.value)">
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
</select>

<div id="blah"> display blah here </div>
<div id="woo"> display woo here </div>
<div id="dope"> display dope here </div>

My AJAX function:

function show_details(eid)
{

    if(window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();

    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()//callback fn
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {

          document.getElementById("blah").innerHTML=xmlhttp.responseText;
          document.getElementById("woo").innerHTML=xmlhttp.responseText;
          document.getElementById("dope").innerHTML=xmlhttp.responseText;


        }
    }

    xmlhttp.open("GET","page2.php?variable4="+eid,true);

    xmlhttp.send();
}

Page2:

<?php
$envv_idd=$_GET["variable4"];

//does operation blah & returns $x

$x= value of blah;
echo $x;

//does operation woo & returns $y

$y= value of woo ;
echo $y;

//does operation dope& returns $z

$z= value of dope;
echo $z;
?>

I want to show $x in div blah, $y in div woo & $z in div dope.

Is there any method?

Upvotes: 0

Views: 212

Answers (1)

Ranjith
Ranjith

Reputation: 2819

$x= value of blah;
$y= value of woo ;
$z= value of dope;

$xyz = array(
         'x' => $x,
         'y' => $y,
         'z' => $z
       );

echo json_encode($xyz);

In your script

if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
    // Your xmlhttp.responseText message returned json value like this
    // {"x":"x text", "y":"y text", "z":"z text"} 

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

    document.getElementById("blah").innerHTML= jsonStr.x;
    document.getElementById("woo").innerHTML = jsonStr.y;
    document.getElementById("dope").innerHTML= jsonStr.z;
}

Upvotes: 2

Related Questions