April 18, 2012

Pass multiple variables to AJAX onchange select

Question by Student

I am looking at this script from W3schools.com (Ajax, PHP and Mysql)
http://www.w3schools.com/php/php_ajax_database.asp

<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  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("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

This shows a simple select with 4 values.

And this is the PHP script.

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', '*', '*');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

Now I understand what it does and how it works, but let’s say that I want to pass 3 more variables to the PHP script, when someone changes the value of the selectbox, how do I do that??

Answer by Simon at mso.net

Following on from my comments, here’s an example that takes the values from 2 selects, and submits an ajax call when both are filled in

// Notice the arguments are gone at the moment
function showUser() {
    // Retrieve values from the selects
    var u = document.getElementByID('userSelect').value;
    var g = document.getElementByID('groupSelect').value;

    if (u=="" || g == "") {
        document.getElementById("txtHint").innerHTML="";
        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("txtHint").innerHTML=xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET","getuser.php?u="+u+"&g="+g,true);
    xmlhttp.send();
}

And then the basic form

<form>
    <select name="users" id="userSelect" onchange="showUser()">
        <option value="">Select a person:</option>
        <option value="1">Peter Griffin</option>
        <option value="2">Lois Griffin</option>
        <option value="3">Glenn Quagmire</option>
        <option value="4">Joseph Swanson</option>
    </select>
    <select name="groups" id="groupSelect" onchange="showUser()">
        <option value="">Select a group:</option>
        <option value="a">Aerosmith</option>
        <option value="k">Kiss</option>
        <option value="l">Led Zeppelin</option>
        <option value="m">Metallica</option>
    </select>
</form>

This is not a fantastic option though, and as mentioned would recommend that you into using a framework such as jQuery ( http://jquery.com/ ) as you will be able to spend more time on the logic rather than ensuring browser compatibility

However you go about it though, it doesn’t hurt to experiment so just give some things a try and see what happens (so long as you aren’t deleting live data, anyway)

Answer by Starx

In order to send mutliple values, you have change your query string accordingly.

xmlhttp.open("GET","getuser.php?q="+str,true);

To, something like

xmlhttp.open("GET","getuser.php?q="+str+"&nextvar="+value1,true);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!