Ajax and PHP

AJAX and PHP

To make ajax and php output your desired data from a mysql, you will need 3 files;
a) main php file with a form and javascript ajax function
b) functions file which has the dynamic drop down menu
c) second php file which handles the GET variable from the url.

How To

1) Have a php function that has select box with a unique name and onchange javascript function like. The drop down menu is dynamic.

function pulldowns() {

echo '<select name="listings" onchange="pulldownit(this.value)">';
$command= "SELECT col1, col2, col3 from country ORDER BY membername ASC";
$rows = array();
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

//echo $row['col1'];
$name2=$row['col2'];
$name =$row['col3'];
echo "<option value=\"$name\" >$name2</option>\n";
}
}
echo '</select>';

2) When an option is selected the ajax call is made. The desired drop down option is the value which gets passed into the javascript function pulldownit(). STR is the value selected. Now ajax goes to work with the string value.

The ajax call opens the desired file with xmlhttp.open("GET","getupdate.php?formname="+str,true);

<script type="text/javascript">
function pulldownit(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","getupdate.php?formname="+str,true);

xmlhttp.send();
}
</script>

The getupdate.php file passes the value into the url. Then, queries run based on the value selected. Change the value and that changes the str value in the url. Voila...fast synchronous output.

3) Set a variable for the get value with the php file which is called
//The getupdate.php file sets avariable to $_GET'['formname']
$formname=$_GET["formname"];

4) Get any data from the database with that variable.