Open In App

XMLHttpRequest.responseType Property

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

XMLHttpRequest is a JavaScript API that enables web developers to send HTTP requests to a server and receive data in response without having to reload the entire page. It’s commonly used in the development of dynamic web applications, which can retrieve data from a server in the background and update the webpage without disrupting the user experience.

To illustrate how XMLHttpRequest works, let’s consider an example where you’re building a website that displays the current weather for a particular location. You can use the XMLHttpRequest API to send a request to a weather API server, which will respond with a JSON object containing the weather data. You can then parse the JSON document using JavaScript and display the relevant weather information on your webpage.

XMLHttpRequest.responseType is an attribute of the XMLHttpRequest object that specifies the type of response that the server should return. For instance, let’s assume you’re designing a weather application that retrieves weather data for a specific region using an API. To display the current temperature on the application dashboard, you can use the XMLHttpRequest object to send a GET request to the weather API, setting the responseType attribute to ‘json’ since the API delivers weather data as a JSON object.

Once the data has been retrieved, you can use dot notation to access the current temperature attribute of the JSON object, which can then be displayed on the dashboard of your weather application.

Syntax: The following is the syntax for using XMLHttpRequest.responseType property:

XMLHttpRequest.responseType = value;

Values: Below are the values and their corresponding syntax that can be used with this property to generate an appropriate response.

  • empty string: This is the default value for XMLHttpRequest.responseType. When the response type is set to an empty string, the response property of the XMLHttpRequest object will contain the response as a string. 
  • arraybuffer: When the response type is set to “arraybuffer”, the response property of the XMLHttpRequest object will contain the response as an ArrayBuffer object. 
  • blob: When the response type is set to “blob”, the response property of the XMLHttpRequest object will contain the response as a Blob object.
  • document: When the response type is set to “document”, the response property of the XMLHttpRequest object will contain the response as an HTML Document object.  
  • json: When the response type is set to “JSON”, the response property of the XMLHttpRequest object will contain the response as a JavaScript object that has been parsed from a JSON string. 
  • text: When the response type is set to “text”, the response property of the XMLHttpRequest object will contain the response as a string. 

Syntax: 

XMLHttpRequest.responseType = '';
XMLHttpRequest.responseType = 'arraybuffer';
XMLHttpRequest.responseType = 'blob';
XMLHttpRequest.responseType = 'document';
XMLHttpRequest.responseType = 'json';
XMLHttpRequest.responseType = 'text';

Example 1: Let’s create an XMLHttpRequest object and request the JSON data from the server. Instead of a server, we created a GeeksforGeeks.json file which contains the following JSON object.

{
    "courses" : [{
        "course_id":101,
        "title": "Data Structures and Algorithms",
        "description": "DSA Self Paced Course – Basic to Advanced",
        "price":1000,
        "discountPercentage": 80,
        "rating": 4.69
    },
    {
        "course_id": 102,
        "title": "Web Development",
        "description": "Full Stack Development Self Paced Course – Basic to Advanced",
        "price": 3000,
        "discountPercentage": 70,
        "rating": 4.0
    }]
}

Getting the response from GeeksforGeeks.json and updating the innerHTML of the div element that we have used in our index.html file:

Here is the code which contains the HTML part and the Javascript method which requests data from the server. To get a JSON object as a response we used XMLHttpRequest.responseType = ‘json’; property.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
  
    <h3>
        XMLHttpRequest.responseType = "json" property
    </h3>
  
    <div id="resonse_box" 
        style="border: 2px solid gray; 
               width:400px; height:auto; 
               padding:20px; 
               border-radius:0.5rem; ">
        Waiting for response from server ...
    </div><br>
  
    <button onclick="callxmlrequest()" 
        style="padding:0.5rem; 
               background-color:rgba(2, 2, 174, 0.719); 
               border:0px; border-radius:0.3rem; 
               color:white; 
               cursor:pointer">
        ClickMe to get Response
    </button>
  
    <script>
        const callxmlrequest = () => {
  
            // Create a new XMLHttpRequest object - 
            let XMLHttpRequest_object 
                = new XMLHttpRequest();
  
            // Set the Response type - 
            XMLHttpRequest_object.responseType = "json";
  
            // Set up a callback function to 
            // handle the response - 
            XMLHttpRequest_object.onload = function () {
                if (XMLHttpRequest_object.status === 200) {
                    var res = JSON.stringify(
                        XMLHttpRequest_object.response);
                    document.getElementById(
                        "resonse_box").innerHTML = res;
                } else {
                    document.getElementById("resonse_box")
                        .innerHTML = "Request Failed!";
                }
            };
  
            // Open a new request with the GET 
            // method and the URL of the server
            XMLHttpRequest_object.open(
                'GET', 
                './GeeksforGeeks.json'
            );
  
            // Send the request to the server
            XMLHttpRequest_object.send();
        }
    </script>
</body>
  
</html>


Output:

 

Example 2: In this example, we are requesting an HTML document using XMLHttpRequest call and XMLHttpRequest.responseType = ‘document’ property. We created an HTML page with basic tags and provide the link to the function for a response. After getting the response, convert it into a string and update the InnerHTML of the element.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
  
    <h3>
        XMLHttpRequest.responseType = "document" property
    </h3>
  
    <div id="resonse_box" style="border: 2px solid gray; 
           width:600px; height:auto; 
           padding:20px; 
           border-radius:0.5rem; ">
  
        Waiting for response from server .....
  
    </div><br>
    <button onclick="callxmlrequest()" 
        style="padding:0.5rem; 
               background-color:rgba(2, 2, 174, 0.719); 
               border:0px; border-radius:0.3rem; 
               color:white; cursor:pointer">
        Click Me to get Response
    </button>
  
    <script>
        const callxmlrequest = () => {
  
            // Create a new XMLHttpRequest object - 
            let XMLHttpRequest_object = new XMLHttpRequest();
  
            // Set the Response type - 
            XMLHttpRequest_object.responseType = "document";
  
            // Set up a callback function to handle the response - 
            XMLHttpRequest_object.onload = function () {
                if (XMLHttpRequest_object.status === 200) {
  
                    var res = new XMLSerializer()
                        .serializeToString(XMLHttpRequest_object.response);
                    document.getElementById("resonse_box").innerHTML = res;
                } else {
                    document.getElementById("resonse_box")
                        .innerHTML = "Request Failed!";
                }
            };
  
            // Open a new request with the GET 
            // method and the URL of the server
            XMLHttpRequest_object.open('GET', './GFG.html');
  
            // Send the request to the server
            XMLHttpRequest_object.send();
        }
    </script>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads