Open In App

XMLHttpRequest.responseType Property

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.

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.




<!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.




<!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:

 


Article Tags :