How to Use XMLHttpRequest in JavaScript?

The XMLHttpRequest is used to get XML files from a server or from a request in JavaScript. This article with code example teaches you how to use the XMLHttpRequest in JavaScript.

What is XMLHttpRequest?

The XMLHttpRequest object is useful if you want to send and retrieve data from a server without reloading the current page.

  • XMLHttpRequest is used for retrieving XML files or pure text content from a server.
  • XMLHttpRequest provides an easy way to retrieve data at a URL.
  • Despite its name, XMLHttpRequest can retrieve any data, not just XML, and it supports protocols other than HTTP (including file and FTP).
  • JavaScript code loaded in the client browser can request additional data from the Web server using the XMLHttpRequest object.

How to use XMLHttpRequest?

XMLHttpRequest makes sending HTTP requests very easy. You create an instance of the object, open a URL, and send the request. The HTTP status of the result, as well as the result's contents, is available in the request object when the transaction is completed. This page outlines some of the common and even slightly obscure use cases for this powerful JavaScript object.

In short, first, initialize an XMLHttpRequest object with the open method, then specify the necessary request headers with the setRequestHeader method and finally send the request with the send method.

Example

Here is example:

<html xmlns="http://www.w3.org/1999/xhtml">    
    <head runat="server">    
        <title></title>    
         
        <script type="text/javascript" language="javascript">    
            function GetDataFromAotherPage() {    
                var objReq = new XMLHttpRequest();    
                objReq.open("GET", "Default2.aspx", false);    
                objReq.send(null);    
                alert(objReq.responseText);    
                return false;    
            }    
        </script>    
         
    </head>    
    <body>    
        <form id="form1" runat="server">    
        <div>    
            <asp:Button ID="btnClickMe" runat="server" OnClientClick="return GetDataFromAotherPage();"    
                Text="Click Me" />    
        </div>    
        </form>    
    </body>    
</html> 

 

 
Description
  1. var objReq = new XMLHttpRequest();
     
    This will create an "XMLHttpRequest" object.
     
  2. objReq.open("GET", "Default2.aspx", false);
     
    The Open() method will initialize an HTTP request for sending. The syntax of the "open" method is as follows:
     
    objReq.open(method, URL, async, user, password);
     
    • Method: Required. A string that specifies the HTTP method (GET, POST, DELETE, HEAD, OPTIONS, PUT) to use. This parameter is case-insensitive.
    • URL: Required. A string that specifies the URL where the request needs to be sent. The specified URL must be in the same domain as the current document.
    • Async: Optional. Boolean that specifies whether the request needs to be handled asynchronously or not. Two values are true and false. 
       
      True (asynchronous): If you use an asynchronous data transfer then register the onreadystatechange event before you send the request. The onreadystatechange event fires every time the state of the request changes.
       
      False (synchronous): In the case of synchronous data transfers, the send method does not return until the response arrives. Do not use this type of data transfer if you do not want to keep the user waiting.
       
    • User: Optional. A string that specifies the name of the user for authentication. The default is an empty string.
    • Password: Optional. String that specifies the password of the user for authentication. The default is an empty string.
  3. objReq.send(null);
     
    The Send() method will send an HTTP request to the server. The syntax for the "send" method is as follows:
     
    objReq.send(messageBody);
     
    • MessageBody: Optional. A string that specifies the body of the request. The default is an empty string. In the case of GET requests (see the method parameter of the open method) this value is ignored, the request body is always empty.
  4. objReq.responseText
     
    Response Text will return the body of the server's response as a string. This property is read-only. 
Output
  1. If you run the code above or the attachment code, the page will be displayed with a button on it.
  2. When you click on the button a pop-up window will be opened with the following output:
     
    XMLHttpRequest.jpg
I hope you will enjoy the article. Thank you.