Ajax and XMLHttpRequest are technologies that make it possible to load data from the server and dynamically update the user interface without reloading the entire page.
Ajax is mainly used with jQuery and provides an easy way to perform asynchronous requests and process the responses. However, it is also possible to use Ajax without jQuery by using the XMLHttpRequest object directly.
XMLHttpRequest allows you to go deeper into the processing of requests and responses and have more control over the request and response. It also enables the processing of data in various formats such as text, JSON or ArrayBuffer.
Both technologies improve the user experience and make it possible to implement more complex functionalities in web applications.
An example with Ajax
In the following example we use jQueryto create a GET request to the file "content.php
" and send the result in a Div element display:
<div id="result"></div>
<script>
setInterval(function() {
$.ajax({
type: "GET",
url: "content.php",
success: function(response) {
$("#result").html(response);
}
});
}, 1000);
</script>
The function setInterval
sends all 1000 milliseconds (every second) one GET
-Request to the file "content.php
". If the request is successful, the response from the server is entered in the div element with the ID #result
inserted.
For something to be displayed, the "content.php
" a return value
to the file. As a simple example, the following text can be written to the file in order to be able to process the answer correctly:
This is a very minimal example, but it shows how easy it is to dynamically update a user interface with Ajax. You can also send data to a server and process its response to implement more complex functionality.
An example with XMLHttpRequest
The following example uses a XMLHttpRequest objectto optimise the System time and the CPU utilisation of a server. The result is then displayed again in a Div element displayed:
<div id="result"></div>
<script>
setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "serverinfo.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML = "Systemzeit: " + response.time + "<br> CPU Auslastung: " + response.cpu + "%";
}
}
xhr.send();
}, 1000);
</script>
The function setInterval
also sends here all 1000 milliseconds (every second) one GET
-Request to the file "serverinfo.php
". Whenever the request is successful, the response from the server is written to the Div element with the ID #result
inserted / updated again.
The serverinfo.php
must look like this for everything to work:
The Advantage from XMLHttpRequest opposite jQuery.ajax is that it more control over the Request and the Answer is available. As an example, an XML request can be used in addition to the ajax request for the readyState
and the status
of the request checkedare used. This ensures that the response is valid before it is processed. In addition, the response can also be sent directly as text or even as a ArrayBuffer
and process them, instead of first being placed in a JSON object to have to convert.
Example of an all-in-one PHP file - XMLHttpRequest
The following example is intended to show how a single «index.php
" file processes both the request and the response for a dynamic update of metrics of a Linux server. This file uses the XMLHttpRequest objectto give yourself all 5 seconds on the basis of a GET
-requests. The metrics are then displayed again in the Div element with the ID #result
displayed.
<div id="result"></div>
<script>
setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "index.php?metrics=true", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
}
xhr.send();
}, 5000);
</script>
<?php
if (isset($_GET['metrics']) && $_GET['metrics'] == 'true') {
$cpu = sys_getloadavg()[0] * 100;
$memory = round(shell_exec("free | grep Mem | awk '{print $3/$2 * 100.0}'"), 2);
$disk = round(shell_exec("df -h / | awk '{print $5}'"), 2);
echo "CPU Auslastung: " . $cpu . "%<br>";
echo "Speicher Auslastung: " . $memory . "%<br>";
echo "Festplatten Auslastung: " . $disk . "%<br>";
exit();
}
?>
The setInterval
Function every 5 seconds (5000 milliseconds) a GET
-Request with the parameter "metrics=true
" to the file "index.php
". Only if the request is successful is the server's response written to the Div element with the ID #result
inserted.
The PHP query checks whether the parameter "metrics
" with the value true
and then calculates the CPU utilisation, memory utilisation and hard disk utilisation of the server. The results are returned and the execution of the scripts is terminated.
This example was also kept very trivial. It is intended to be a simple example that shows that there are also more extensive options for collecting and displaying metrics from a server. It is also important that the server-side requests are always designed securely to prevent unauthorised access.
Conclusion
Ajax as well as XMLHttpRequest are useful technologies for the development of dynamic and interactive web applications. While Ajax one offers an easier way to carry out enquiries and process the responsesoffers XMLHttpRequest More control and flexibility via the request / response.
Ultimately, the choice of technology depends on the requirements and preferences of the developer.