Asynchronous JavaScript and XML, or AJAX, is a set of methods used to build interactive online applications rather than a single technology. The main concept is to enable communication between PHP scripts running on the web server and JavaScript running on the client’s web browser without the need for a full-page synchronous request and refresh. The user experience is streamlined as a result.
In a normal PHP-based AJAX interaction:
- Client-side JavaScript sends the server an HTTP request. The built-in XMLHttpRequest object or the streamlined techniques offered by JavaScript libraries such as jQuery can be used for this.
- The request is received and processed by a PHP script on the server. PHP can communicate with databases and is ideally suited for producing dynamic web content.
- The PHP script produces output or obtains data, which may be in JSON, XML, or text formats.
- The client receives an HTTP response from the server.
- On the client side After receiving the response, JavaScript uses the information to dynamically update some sections of the webpage without requiring a page reload.
HTML and JavaScript using XMLHttpRequest
A basic HTML page using JavaScript that makes a request to a PHP file is demonstrated in this example. In this example, user input triggers the JavaScript function showHint(), which sends the request via XMLHttpRequest.
<html>
<head>
<style>
span {
color: green;
}
</style>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest(); // Create XMLHttpRequest object
// Define what happens when the ready state changes
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Check if request is complete and successful
document.getElementById("txtHint").innerHTML = xmlhttp.responseText; // Update an element with the response
}
}
// Open and send the request
xmlhttp.open("GET", "php_ajax.php?q=" + str, true); // Request php_ajax.php with parameter 'q'
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
Search courses: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Hint: <span id="txtHint"></span></p>
</body>
</html>
This code calls the showHint() function when the user types in the input field. A GET request is sent to php_ajax.php with the input string as a query parameter q after an XMLHttpRequest object has been created and a function has been set up to handle the response when it is ready.
Server PHP script (php_ajax.php)
After processing the client’s request, this PHP script provides a response.
<?php
// Array with names
$a[] = "Android";
$a[] = "B programming language";
$a[] = "C programming language";
// ... (other names) ...
$a[] = "ZOPL";
// Get the parameter 'q' from the request
$q = $_REQUEST["q"];
$hint = ""; // Initialize hint variable
// Look for a matching name in the array
if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) { // Check if the start of the name matches the query [24]
if ($hint === "") {
$hint = $name; // If this is the first match, set hint
} else {
$hint .= ", " . $name; // If there are other matches, append them
}
}
}
}
// Output the hint, or "no suggestion" if no matches
echo $hint === "" ? "no suggestion" : $hint;
?>
Using $_REQUEST, this PHP script retrieves the value of the q parameter that was supplied in the GET request. Following that, it iterates through a list of names ($a) to see if any of them begin with the input string ($q). The resultant hint string is then echoed back to the browser, where it is shown by the client-side JavaScript.
Using jQuery for AJAX
AJAX request processing is made easier by libraries such as jQuery. You can use methods like $.ajax(), $.get(), or $.getJSON() in instead of XMLHttpRequest.
Using $.getJSON() as an example: On the client side (after adding the jQuery library, inside a <script> block):
// Load a JSON document via HTTP GET
$.getJSON('/example.php', {
'jsonParam' : 'paramValue'
}, function(data, textStatus, jqXHR) {
console.log(data.status); // Process the JSON data received
});
The PHP script on the server side (example.php) would process the jsonParam request and use json_encode(), for example, to produce a JSON answer. A PHP script for AJAX requests that returns a JSON object with a success or failure message and maybe a list of messages is mentioned in one AJAX .
Creating distinct files for styles, JavaScript functions, and extra PHP scripts specifically for managing the AJAX interactions is sometimes required for adding AJAX capabilities to already-existing PHP applications.
Modern, responsive web apps may be created with AJAX, which is powered by server-side languages like PHP and allows for dynamic updates without requiring full-page reloads. Integrating AJAX with PHP include phpbuilder.com, the website of jQuery, and other developer portals.