![]() |
VOOZH | about |
In this article, we will see what is XMLHttpRequest Object, along with knowing their properties with their implementation through the illustrations.
XMLHTTPRequest object is an API that is used for fetching data from the server. XMLHTTPRequest is basically used in Ajax programming. It retrieves any type of data such as JSON, XML, text, etc. It requests for data in the background and updates the page without reloading the page on the client side. An object of XMLHTTPRequest is used for asynchronous communication between client and server.
For security reasons, across domains, modern browsers will not support it. Hence any web page, XML/HTML/txt, or any format page should be located on the same server.
Properties of XMLHttpRequest Object:
We will explore these concepts & understand them through the illustrations.
Example 1: In this example, the page is displayed with the 'Get the contents' button. On clicking the button, onload defines a function to be called. It will try to access gfg.html which is present inside the same server and since it is available, it will take the contents and display them in the <div> tag
Output: Here, we can see that on clicking the button, the load is called & the content of the gfg.html file gets rendered.
Example 2: This example illustrates the onreadystatechange Property that will be invoked when the readyState property changes. Here, we will be using the above gfg.html file.
Explanation: On execution of this, as gfg.html is present in the same server and assuming no issues in retrieving it, we will get the readyState as 4 and response as 200, and hence we can see the below output.
Output:
Note: It is very important to note that the URL that is getting opened must be available on the same server. If not, it will throw cross domain error.
Example 3: In this example, we are using the above code example. The requested page can be an HTML/XML/text file. Here, we will try to fetch the content from an XML file.
Output: From the output, we can see that the content from the XML file gets rendered.
XMLHttpRequest properties are highly useful to open a web page that is present on the same server. Inside the web page, we can keep the necessary information, even like getting the contents from the Rest API call and setting the response from that to the HTML element controls present in the calling file or an XML file.