AJAX is utilized to make increasingly intelligent applications.

AJAX PHP Example

The following model will show how a page can speak with a web server while a client type characters in an information field:


Start composing a name in the info field below:

First name:


Example Explained

In the precedent above, when a client types a character in the information field, a capacity called "showHint()" is executed.

The work is activated by the onkeyup event.

Here is the HTML code:


function showHint(str) {
    on the off chance that (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = work() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        };"GET", "gethint.php?q=" + str, true);

<p><b>Start composing a name in the input field below:</b></p>
First name: <input type="text" onkeyup="showHint(this.value)">
<p>Suggestions: <span id="txtHint"></span></p>

Code explanation:

First, check if the information field is vacant (str.length == 0). In the event that it is, clear the substance of the txtHint placeholder and leave the function.

However, if the information field isn't unfilled, do the following:

  • Create a XMLHttpRequest object
  • Create the capacity to be executed when the server reaction is ready
  • Send the demand off to a PHP record (gethint.php) on the server
  • Notice that q parameter is included gethint.php?q="+str
  • The str variable holds the substance of the information field

The PHP File - "gethint.php"

The PHP document checks a variety of names, and returns the comparing name(s) to the browser:

/Array with names
$a[] = "Merry";
$a[] = " Kunkel";
$a[] = "Emily";
$a[] = "Cazares";
$a[] = "Kenneth";
$a[] = "Thurber";
$a[] = "Brenda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

/get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// query all indications from exhibit if $q is unique in relation to ""
if ($q !== "") {
    $q = strtolower($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";

//Output "no suggestion" if no insight was found or then again yield right qualities
reverberation $hint === "" ? "no suggestion" : $hint;