AJAX is the art of exchanging data with a server, and updating parts of a web page.
It does all of this without reloading the whole page.
This is a massive benefit for user experience and modern web development.
AJAX stands for Asynchronous JavaScript and XML.
In short, AJAX is about loading data in the background.
It displays that data on the webpage without reloading the browser window.
Examples of applications using AJAX: Gmail, Google Maps, YouTube, and Facebook tabs.
When a user triggers an event (like clicking a button), JavaScript creates an XMLHttpRequest object.
This object sends a request to a web server in the background.
The server processes the request, prepares a response, and sends data back to the browser.
JavaScript receives the data and uses the DOM to update the webpage instantly.
Writing regular AJAX code in pure JavaScript can be a bit tricky.
Different browsers might require different code to create the AJAX request.
This forces developers to write extra code to handle cross-browser compatibility.
Fortunately, the jQuery team saw this problem and fixed it.
jQuery provides several powerful methods for AJAX functionality.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server.
You can do this using both HTTP Get and HTTP Post requests.
And best of all, you can load the external data directly into the selected HTML elements of your webpage!
Writing an AJAX request with standard JavaScript takes many lines of complex code.
jQuery condenses all of that into a single, clean method call.
It also automatically handles all the cross-browser bugs and inconsistencies behind the scenes.
This means your code is guaranteed to work on Chrome, Firefox, Safari, and Edge.
// Standard JavaScript AJAX (Too Long)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
// jQuery AJAX (Very Short)
$("#demo").load("ajax_info.txt");
Why is jQuery AJAX preferred over standard JavaScript AJAX?