PHP - AJAX Database
AJAX can be used for interactive communication with a database. The following example will demonstrate how a web page can fetch information from a database with AJAX:
Employee info will be listed here...
When a user selects a user in the dropdown list above, a function called "showEmployee()" is executed. The function is triggered by the "onchange" event:
<html>
<head>
<script type="text/javascript">
function showEmployee(str)
{
var xmlhttp;
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","phpresult.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="">
<select name="customers" onchange="showEmployee(this.value)">
<option value="">Select an Employee:</option>
<option value="1">Putra Angkasa</option>
<option value="2">Bayu Segara</option>
<option value="3">Mega Ayuning</option>
</select>
</form>
<br />
<div id="txtHint">Employee info will be listed here...</div>
</body>
</html>
The showEmployee() function does the following:
- Check if a person is selected
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (q) is added to the URL (with the content of the dropdown list)