AJAX PHP

AJAX with PHP

AJAX is highly useful for communicating interactively with a backend server script.

One of the most common backend server languages used with AJAX is PHP.

Curious about other backend languages? Learn how to achieve the exact same result in our AJAX ASP tutorial.

Creating an Interactive Example

Imagine an HTML input field where a user types a name.

Every time a letter is typed, an AJAX request is instantly fired to a PHP script.

The PHP script checks an array of names and returns a suggestion back to the browser!


The Frontend Code

In the browser, we use the onkeyup event to trigger the AJAX call.

We append the typed letters to the URL using a query string (gethint.php?q=a).

Frontend Input Example:

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;
  }
  // Sending the typed string to the PHP file
  xhttp.open("GET", "gethint.php?q=" + str);
  xhttp.send();
}

The PHP Backend Code

On the server, the gethint.php file reads the q parameter using $_GET["q"].

It runs a loop to check if any stored names start with that exact string.

Finally, it echoes the matching names back to the browser instantly!


Exercise 1 of 1

?

How does an AJAX GET request typically pass user data to a PHP script?