Introduction
In this article, we will be discussing how we can start our journey with AJAX. But, before we can start, we should be very clear about what exactly is this AJAX.
The full form of AJAX is asynchronous Javascript and XML. It is not a programming language, which many of you might be thinking. It helps to establish and maintain the interconnection between client and server. For more details, visit here. In this article, we are only considering AJAX and how we can start and work with AJAX. So, let’s find that out.
Source: Giphy
Using AJAX following work can be performed very easily:
- After the page is loaded, read data from a web server.
- A web page can be updated without even reloading it.
- Sending the data to a web server, in the background.
Let’s take an example to understand better.
<!DOCTYPE html> <html> <body> <div id="practise"> <h2>Demo AJAX example</h2> <button type="button" onclick="loadDoc()">Click here to Change Content</button> </div> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("practise").innerHTML = this.responseText; } xhttp.open("GET", "ajax_info.txt"); xhttp.send(); } </script> </body> </html> |
Output:
Try and compile by yourself with the help of online javascript compiler for better understanding.
After click:
If we look closely at the example, we will find out that the html page is containing a <div> section and a <button>. All the information that is displayed from the server is done in the <div> section. When the button is clicked, the function is called. Then data is requested from the webserver and results are displayed.
AJAX
AJAX is the combination of:
- A browser built-in XMLHttpRequest object( to request data from a web server).
- Javascript and HTML DOM(to display or use the data).
The name AJAX is itself a little misleading. XML might be used by AJAX to transport the data with a web server behind the scenes. This signifies that the web page can be updated without reloading it.
Another advantage of AJAX is that it helps the web pages to update asynchronously by exchanging the data with a web server behind the scenes.