HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

AJAX - Interaction with PHP

To make a truly dynamic website, JavaScript needs to talk to a server-side language like **PHP**. With AJAX, you can send user input to a PHP script, process it on the server (like checking a username availability), and get an answer back instantly.


Sending Data to PHP

Data is usually sent to PHP through the URL (GET) or in the request body (POST). PHP accesses this via the $_GET or $_POST global variables.

function showSuggestion(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    }
    
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
        }
    };
    // Send input 'q' to gethint.php via GET
    xhttp.open("GET", "gethint.php?q=" + str, true);
    xhttp.send();
}

Handling Data on the Server

On the server, the PHP file reads the input, performs logic, and uses echo to send the result back to JavaScript.

<?php
// gethint.php
$q = $_REQUEST["q"];
$hint = "";

// Logic to find matches in a names array
if ($q !== "") {
    $q = strtolower($q);
    $len = strlen($q);
    foreach($names as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

echo $hint === "" ? "no suggestion" : $hint;
?>
Why this is important: Without AJAX, every search query would require refreshing the entire page. With AJAX, only the tiny suggestion text is updated.

Using POST for Security

When sending sensitive data (like passwords) or large amounts of text, always use the POST method.

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "process.php", true);

// POST requires this Header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhttp.send("fname=John&lname=Doe");
Pro Tip: When echoing data from PHP meant for JavaScript, it is a best practice to use json_encode(). This ensures that special characters don't break your front-end scripts.

Key Points to Remember

  • PHP is used for server-side processing that JavaScript cannot do.
  • Data can be sent using XMLHttpRequest.open() with query strings.
  • PHP uses $_GET and $_POST to retrieve the data.
  • The echo command in PHP provides the value for responseText.
  • Always set the Content-type header when sending POST data.