AJAX PHP Example


AJAX helps in making applications more interactive.


AJAX PHP Example

The example below shows how a webpage can talk to a web server as someone types in a box:

Example

Start typing a name in the input field below:

Suggestions:

First name:



Example Explained

In the example shown, when someone types a letter in the input box, a function named showHint() runs.

The action starts when a user releases a key, detected by the onkeyup event.

Here's the code:

Code explanation:

Initially, verify whether the input field is blank (str.length == 0). If it is, erase the content in the txtHint placeholder and end the function.

If the input field has some text, then take the following actions:

  • To make a XMLHttpRequest object:
  • Develop the function that runs when the server's response is prepared.
  • Send a message to a PHP document (gethint.php) stored on the server.
  • Notice how the 'q' parameter is included in the URL as 'gethint.php?q='+str.
  • The "str" variable contains what's typed in the input box.

The PHP File - "gethint.php"

The PHP document looks at a list of names, then sends back the name(s) that match 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;
?>