AJAX PHP

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

AJAX PHP

The following example illustrates how a web page can communicate with a web server while a user types characters in an input field.

Example

<!DOCTYPE html>

<html>

<body>

<h2>The XMLHttpRequest Object</h2>

<h3>Start typing a name in the input field below:</h3>

<p>Suggestions: <span id=”txtHint”></span></p>

<p>First name: <input type=”text” id=”txt1″ onkeyup=”showHint(this.value)”></p>

<script>

function showHint(str) {

  if (str.length == 0) {

document.getElementById(“txtHint”).innerHTML = “”;

    return;

  }

const xhttp = new XMLHttpRequest();

xhttp.onload = function() {

document.getElementById(“txtHint”).innerHTML =

    this.responseText;

  }

  xhttp.open(“GET”, “gethint.php?q=”+str);

  xhttp.send();  

}

</script>

</body>

</html>

Output

The XMLHttpRequest Object

Start typing a name in the input field below:

Suggestions:

First name:

Code explanation

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

In case the input field is not empty, then process the following:

  • Built an XMLHttpRequest object.
  • Built the function to be executed when the server response is ready.
  • Send the request off to a PHP file (gethint.php) on the server.
  • Notice that q parameter is added gethint.php?q=”+str.
  • The str variable stores the content of the input field.

The PHP File – “gethint.php”

The PHP file checks an array of names, and returns the corresponding 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;

?>