PHP Ajax Tutorial

PHP Ajax Tutorial

The following tutorial for php and ajax will show how a drop down menu can be created with php and ajax.The example uses 2 files. The first file, creates a menu that changes when a user selects a value. The second file takes in the id of the person with the email address and makes a new drop down menu based on the id. In this case, the new options are those names with an id greater than the $_GET['mystring'] and less than that value + 4.

File#1

<?php include("connect.inc");
$db = public_db_connect();
?>
<html>
<head>
<script type="text/javascript">

function listMembers(str)
{
if (str=="")
{
document.getElementById("my_text").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("my_text").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax-get.php?mystring="+str,true);
xmlhttp.send();
//alert(str);
}
</script>
</head>

<?php
function tablesort_menu() {
global $db;
echo '<select id="my_text" name="members" onchange="listMembers(this.value)">';
$command= "SELECT DISTINCT id, email FROM table_sort ";
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

$id=$row['id'];
$name=$row['email'];

echo "<option value=\"$id\" >$name</option>\n";
}
}
echo '</select>';
}

?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>"> <?php
tablesort_menu(); ?>
</form>
</html>

File #2

<?php include("connect.inc");
$db = public_db_connect();
$myid = $_GET['mystring'];
$myid2 = $myid + 4;

$command2="SELECT firstname, lastname FROM table_sort WHERE id>'$myid' AND id<'$myid2' ORDER BY firstname ASC";
$result2 = mysqli_query($db, $command2);
echo '<select name="name_list">';
while($row = mysqli_fetch_assoc($result2)){
$first_name=$row['firstname'];
$last_name=$row['lastname'];
echo "<option value=\"$first_name\" >$first_name</option>\n";

}
echo '</select>';

mysqli_close($db);
?>