Advance JavaScript

JavaScript – Ajax


AJAX is a technique for updating the page components without reloading the whole page. We can create fast and dynamic web page by exchanging data with a web server behind the scenes.

AJAX stands for: Asynchronous, JavaScript, and XML

AJAX is not a programming language. It uses browser built-in XMLHttpRequest object to request data from a web server. And with the help of HTML DOM and JavaScript displays the data or use the data.

In JavaScript, there is a special class ‘XMLHttpRequest’ which helps in exchanging data with the server in the background.

XMLHttpRequest fetches data from the server and responds the data in the following format:

  • Text File
  • XML Data
  • JSON Data

An AJAX request is completed with the help of JavaScript XMLHttpRequest, in 5 states:

  • 0 : The request is not initialized.
  • 1 : The server connection has been set up.
  • 2 : The request has been sent.
  • 3 : The request is in process.
  • 4 : The request is complete and response is ready.

Once the request is completed, server sends the status and response.

The status returned by the web server might be one of the following:

  • 200 : ‘OK’ – It means server has been responded for what you have requested.
  • 403 : ‘Forbidden’ – It means server is not responding anything.
  • 404 : ‘Not Found’ – It means server didn’t find any data related to your request.

If we have request for text then it returns response in responseText, other it will give response in XML.

XMLHttpRequest Object Methods

  1. new XMLHttpRequest : It creates a new XMLHttpRequest object.
  2. open(method, url, async, user, pwd) : It specifies the request to the server for data access.
    • method: the request type can be POST or GET.
    • url : the file location
    • async : true/false, true => asynchronous, false => synchronous.
  3. send() : Sends the request to the server. Used for GET requests.
  4. send(string) : Send the request to the server. Used for POST requests.

XMLHttpRequest Object Methods

  1. onload : It defined a function that should be called once the request is received.
  2. onreadystatechange : It defines a function to be called whenever the readyState property changes.
  3. readyState : It consists the status of XMLHttpRequest.
  4. responseText : Returns the response data as a string.
  5. responseXML : Returns the response data as XML data.
  6. status : Returns the server status against request.
  7. statusText : Returns the status-text (‘OK’ or ‘Not Found’)

JavaScript AJAX Syntax

Let us understand how to write AJAX Syntax

Step 1: Firstly we will create an object of class XMLHttpRequest

const xhttp = new XMLHttpRequest();

Step 2: We will direct which file to be open and what will be request mode with async status (true or false).

xhttp.open('GET', 'filename.txt', true);

Step 3: Then we send the request

xhttp.send();

Step 4: We keep checking the ready state change against the request sent. If the read state comes and want to show response text in some html element, Then

xhttp.onreadystatechange = function(){
    if(this.readyState ==4 && this.status == 200){
        document.getElementById('demo').innerHTML = this.responseText;
    }
};
const xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){
    if(this.readyState ==4 && this.status == 200){
        document.getElementById('demo').innerHTML = this.responseText;
    }
};

xhttp.open('GET', 'filename.txt', true);
xhttp.send();

AJAX request and response behavior using a XAMPP Server. You can try with live server also. But for AJAX request check, it is mandatory to have a server either it is local server or live server.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - AJAX</title>
</head>
<body>
    <p id="demo"> Here you can see the loaded data.</p>
    <button onClick="loadData()">Click me</button>
    <script>
        function loadData()
        {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if(this.readyState == 4 && this.status == 200){
                    document.getElementById('demo').innerHTML = this.responseText;
                }else if(this.readyState == 4 && this.status == 404){
                    document.getElementById('demo').innerHTML = 'File not Found on Server.';
                }
            }
            xhttp.open('GET', "response_text.txt", true);
            xhttp.send();

        }
    </script>
</body>
</html>

Here in the above example, if you click on the button, it will fetch the content of ‘response_text’ file and respond the same. That response will be write into html element having id = ‘demo’. Please try it your end.