JS AsyncLesson #281

AJAX PHP Example

AJAX is used to create more interactive applications.

AJAX is used to create more interactive applications.


Share

AJAX PHP Example

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


Example Explained

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

The function is triggered by the onkeyup event.

Here is the code:

Example

Example Code

html
Try it Yourself
Start typing a name in the input field below:

Suggestions:

First name:

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();

  }

}

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.

However, if the input field is not empty, do the following:

  • Create an XMLHttpRequest object
  • Create 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 holds 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:

Interactive Code Examples

JS Example 2

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: