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.
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();
}
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;
?>
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");
json_encode(). This ensures that special characters don't
break your front-end scripts.
responseText.