PHP and AJAX

PHP and AJAX

To demonstrate how easily PHP and AJAX can communicate, let's create a simple application.

We will build an input field where a user can type a name. As they type, JavaScript will send their input to a PHP script using AJAX, and the PHP script will return a suggested name instantly!


1. The Frontend (HTML & JavaScript)

First, we create an HTML page with an input field. We add an onkeyup event to the input, so every time a key is pressed, it triggers a JavaScript function called showHint().

<html>
<head>
<script>
function showHint(str) {
  if (str.length == 0) {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    // Create the AJAX object
    var xmlhttp = new XMLHttpRequest();
    
// Define what happens when the response is ready
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("txtHint").innerHTML = this.responseText;
  }
};

// Open the connection and send the request to PHP
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();

} } </script> </head> <body> <p><b>Start typing a name in the input field below:</b></p> <form> First name: <input type="text" onkeyup="showHint(this.value)"> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>


2. The Backend (PHP)

Now we create the gethint.php file on our server. This script looks at the data sent by the AJAX request ($_GET['q']), searches through an array of names, and returns a match.

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";

// Get the parameter sent from JavaScript $q = $_REQUEST["q"]; $hint = "";

// Check if $q is not empty, and find matches 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 the correct values echo $hint === "" ? "no suggestion" : $hint; ?>

This seamless back-and-forth is the foundation of modern web applications!


Exercise

?

Which JavaScript object is used to send asynchronous requests to a PHP server?