Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

AJAX PHP

AJAX PHP Example

The following example shows how a web page can interact with a web server as the user types characters into an input field.

Example

Begin typing a name in the input field below:

Suggestions:

First name:

Example Explained

In the example above, when the user types a character in the input field, the showHint() function is executed.

The function is triggered by the onkeyup event.

Here’s the code:

Example

<p>Start typing a name in the input field below:</p>
<p>Suggestions: <span id=”txtHint”></span></p>

<form>
First name: <input type=”text” onkeyup=”showHint(this.value)”>
</form>

<script>
function showHint(str) {
  if (str.length == 0) {
    document.getElementById(“txtHint”).innerHTML = “”;
    return;
  } else {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
      document.getElementById(“txtHint”).innerHTML = this.responseText;
    }
  xmlhttp.open(“GET”“gethint.php?q=” + str);
  xmlhttp.send();
  }
}
</script>

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.

If the input field is not empty, perform the following steps:

  1. Create an XMLHttpRequest object.
  2. Define the function to be executed when the server’s response is ready.
  3. Send the request to a PHP file (gethint.php) on the server.
  4. Notice that the q parameter is added to gethint.php?q="+str, where the str variable holds the content of the input field.

The PHP File – “gethint.php”

The PHP file checks an array of names and returns the matching name(s) to the browser.

<?php
// Array with names
$a[] = “Anna”;
$a[] = “Brittany”;
$a[] = “Cinderella”;
$a[] = “Diana”;
$a[] = “Eva”;
$a[] = “Fiona”;
$a[] = “Gunda”;
$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 = “”;

// lookup all hints from array if $q is different from “”
if ($q !== “”) {
  $q = strtolower($q);
  $len=strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
      if ($hint === “”) {
        $hint = $name;
      } else {
        $hint .= “, $name”;
      }
    }
  }
}

// Output “no suggestion” if no hint was found or output correct values
echo $hint === “” ? “no suggestion” : $hint;
?>