简体   繁体   中英

How to fill dropdown box dynamically from database without submitting form and page refresh using AJAX in PHP?

I have a PHP file in which there is a form and which has two Select drop down box. The first select box is filled with some value.

The Secont select box is empty.

As per requirement if some value is selected from first drop down box the second box should be get filled with some values from database.

I want to achive this using AJAX.

I got a code from http://www.w3school.com site. But in following that there is only one dropdown box and on onchange event the related values of selected value are showed in table format.I can replace that html code for table in the code with my second select box. But as per requirement I want to show second select dropdown box empty before selection which should get filled as per the selection in first select box dynamically and from database. So friends please tell me how to solve this problem. If you dont understand the following code because of formatting; then the same code that I got from http://www.w3school.com site is on the following link on same site.

http://www.w3schools.com/php/php_ajax_database.asp

This is the HTML page with ajax code

<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 is the PHP file which is located on server and get called using AJAX and fetches the values from database

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
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);
?>

Please Guide me friends. Thank You!

instead of echoing the results back in table row form, perhaps send them back in JSON format like this. you should also do some sort of check against SQL injection through casting (if your 'q' variable is a number) or mysql_real_escape_string().

PHP file:

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT `yourFieldName`, `yourFieldValue` FROM `yourTable` WHERE id = '".$q."'";
$result = mysql_query($sql);
$i = 0;
while ( $row = mysql_fetch_assoc($result) )
{
    $return[$i] = $row;
    $i++
}
$return["size"] = $i;
mysql_close($con);
echo json_encode($return);
?>

now all that needs changed in the javascript file is this:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var responses = JSON.parse(xmlhttp.responseText);
        var size = responses.size;
        var selectBox =document.getElementById("yourSecondSelectBox");

        //clear any previous entries
        selectBox.options.length=0;
        for (var i = 0; i < size; i++){
            selectBox.options[i]=new Option(responses.i.yourFieldName, responses.i.yourFieldValue, false, false)
        }
    }
}

of course, you need to download and include the JSON js file in your html 'head' tag. alternatively, you could include jquery and use their built in AJAX and JSON support, but that will require more research on your part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM