AJAX is used to create more interactive applications.

AJAX PHP example

The following example demonstrates how a web page can communicate with a web server when a user types characters in an input box:


Try entering a name in the input box, such as Anna:


Return value:

Example explanation-HTML page

When the user types a character into the input box above, the "showHint ()" function is executed. This function is triggered by the "onkeyup" event:

function showHint(str)
    if (str.length==0)
    if (window.XMLHttpRequest)
        //IE7+, Firefox, Chrome, Opera, Safari Browser executed code
        xmlhttp=new XMLHttpRequest();
        //IE6, IE5 Browser executed code
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlhttp.readyState==4 && xmlhttp.status==200)

<p><b>Enter a name in the input box:</b></p>
Name: <input type="text" onkeyup="showHint(this.value)">
<p>return value: <span id="txtHint"></span></p>


Source code explanation:

If the input box is empty (str.length == 0), the function clears the contents of the txtHint placeholder and exits the function.

If the input box is not empty, showHint () performs the following steps:

  • Creating an XMLHttpRequest object
  • Create a function to be executed when the server response is ready
  • Send a request to a file on the server
  • Please note the parameter (q) added to the end of the URL (including the content of the input box)

PHP file

The above server page called via JavaScript is a PHP file named "gethint.php".

The source code in "gethint.php" checks the array of names and returns the corresponding names to the browser:

//Fill names into an array

//Get the q parameter from the request URL

//Find if matched by value, ifq>0
if (strlen($q) > 0)
    for($i=0; $i<count($a); $i++)
        if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
            if ($hint=="")
                $hint=$hint." , ".$a[$i];

//If there is no matching value set the output to "no suggestion" 
if ($hint == "")
    $response="no suggestion";

//Output return value
echo $response;

Explanation: If JavaScript sends any text (i.e. strlen ($ q) > 0),Will happen:

  1. Find names that match characters sent by JavaScript
  2. If no match is found, set the response string to "no suggestion"
  3. If one or more matching names are found, set the response string with all names
  4. Send response to "txtHint" placeholder