What is AJAX? How is it used?
AJAX is a word I often hear in my company, but I did not really understand the meaning or the pros and cons of it. So, I checked out the meaning of it and how it is used. As it turns out, it is just technology that most developers, including myself, use on a daily basis.
What is AJAX?
AJAX stands for "Asynchronous JavaScript and XML", and this makes it possible to create a better user experience on the browser. The name only includes XML, but JSON is more commonly used. In a nutshell, this is a technology in which JavaScript can send requests asynchronously to the server. Without using AJAX, the browser needs to wait every time it sends a request. This asynchronous feature makes the user experience better.
If you use JavaScript for the client side, surely you have used fetch or axios. By using either of them, an AJAX request can be made. Axios sends requests without changing the state of HTML on the browser, and once it receives the response, it can update HTML dynamically or be used in another function.
Here is a simple example of an AJAX request by Axios.
// Make an AJAX request using Axios
axios.get('/api/data')
.then(function(response) {
// Update the page with the response data
var data = response.data;
document.getElementById('result').innerHTML = data;
})
.catch(function(error) {
console.error('Error:', error);
});
Presumably, it is rare to use synchronous request, but if needed, following code can be used.
// Make a synchronous AJAX request using XMLHttpRequest
var request = new XMLHttpRequest();
request.open('GET', '/api/data', false); // false sets request to synchronous
request.send();
if (request.status === 200) {
// Update the page with the response data
var data = request.responseText;
document.getElementById('result').innerHTML = data;
} else {
console.error('Error:', request.status);
}