AJAX - PHP
AJAX is used to create more interactive applications. The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:
PHP AJAX Example
Start typing a name in the input field below:
Suggestions:
When a user types a character in the input field above, the function "showHint()" is executed. The function is triggered by the "onkeyup" event:
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
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","autocomplete.php?q="+str,true);
xmlhttp.send();
}
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the txtHint placeholder and exits the function.
If the input field is not empty, the showHint() function executes the following:
- 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 input field)
Below is the code above rewritten in PHP.
Note: To run the example in PHP, change the value of the url variable (in the HTML file) from "gethint.asp" to "gethint.php".
0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i
Download PHP AJAX Example