Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Ajax XMLHttpRequest

JS Ajax XMLHttpRequest Object

The XMLHttpRequest object can be used to exchange data with a web server behind the scenes.

The XMLHttpRequest Object

The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

The keystone of AJAX is the XMLHttpRequest object.

  • Create an XMLHttpRequest object
  • Define a callback function
  • Open the XMLHttpRequest object
  • Send a Request to a server
Create an XMLHttpRequest Object

The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

					 
        
          const xhttp = new XMLHttpRequest();
        
      
Define a Callback Function

A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the response is ready.

					 
        
          xhttp.onload = function() {
            // Do something when the response is ready
          }
        
      
Send a Request

To send a request to a server, you can use the open() and send() methods of the XMLHttpRequest object.

					 
        
          xhttp.open("GET", "ajax_info.txt");
          xhttp.send();
        
      
Combine Example
					 
        
          // Create an XMLHttpRequest object
          const xhttp = new XMLHttpRequest();

          // Define a callback function
          xhttp.onload = function() {
            // Here you can use the Data
          }

          // Send a request
          xhttp.open("GET", "ajax_info.txt");
          xhttp.send();
        
      
Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

XMLHttpRequest Object Methods
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method, url, async, user, psw) Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server. Used for GET requests
send(string) Sends the request to the server. Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
XMLHttpRequest Object Properties
Property Description
onload Defines a function to be called when the request is received (loaded)
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
statusText Returns the status-text (e.g. "OK" or "Not Found")
The onload Property

With the XMLHttpRequest object you can define a callback function to be executed when the request receives an answer.

The function is defined in the onload property of the XMLHttpRequest object.

					 
        
          xhttp.onload = function() {
            document.getElementById("demo").innerHTML = this.responseText;
          }
          xhttp.open("GET", "ajax_info.txt");
          xhttp.send();
        
      
Multiple Callback Functions

If you have more than one AJAX task in a website, you should create one function for executing the XMLHttpRequest object, and one callback function for each AJAX task.

The function call should contain the URL and what function to call when the response is ready.

					 
        
          loadDoc("url-1", myFunction1);

          loadDoc("url-2", myFunction2);

          function loadDoc(url, cFunction) {
            const xhttp = new XMLHttpRequest();
            xhttp.onload = function() {cFunction(this);}
            xhttp.open("GET", url);
            xhttp.send();
          }

          function myFunction1(xhttp) {
            // action goes here
          }
          function myFunction2(xhttp) {
            // action goes here
          }
        
      
The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a callback function to be executed when the readyState changes.

The status property and the statusText properties hold the status of the XMLHttpRequest object.

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready.

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.

					 
        
          function loadDoc() {
            const 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");
            xhttp.send();
          }
        
      

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved