Updated April 12, 2023
Definition of XML HttpRequest
XML HTTP Request (XHR)is defined as a built-in object to make an HTTP requests in a server with JavaScript. We could upload and download the files easily as it fetches reliable information from the server. It provides a communication path between a client and a server. With the help of two modes of operations like synchronous and Asynchronous mode, the request progress is done. Without refreshing a complete page this keyword helps to retrieve data from a URL. XHR benefits to updating a web page without refreshing a whole page also take care of all low-level APIs like caching, connection establishment.
Syntax:
A simple syntax looks like b creating a constructor
Var xmlh=new XMLHttpRequest ();
How does HttpRequest Method work in XML?
HTTP request exchanges data between a web browser and a server which in turn returns any information not only an XML also a building block of web applications. Using XHR to send an HTTP request first step is to open a connection to specified the URL and perform a send request. The browser handles the request and does the full life cycle of the connection process. Meanwhile, a response is sent along with a response body and Status code. The workflow of a web page is reduced by XHR as it is done asynchronously with the full fledge of control. XHR has a high-performance transfer communication enabling real-time delivery. XHR can transfer both binary and text files as they have automatic encoding and decoding for datatypes. In this article, we have used a JSON data structure for representing Java Script Objects.
Steps include:
- Creating a Constructor to create an Object.
Var xmlh=new XMLHttpRequest ();
- Importing above in an HTML document.
- Importing Methods which is given below.
XHR requires a timeout to complete the request raised. It specifies a few milliseconds to complete or wait for the application to do the process.
Xr.timeout=4000;
The two listeners that are set to handle the request are open () and send (). We can load XML, HTML files.
In this section, we shall a few methods and their properties of XML HTTP Request. Below we have listed the methods:
- abort () – This method drops the current request progress. It aborts fetching information.
- open (method, URL) – This method opens a request by specifying GET or POST along with the URL scheme.
- open (method, URL, async) – This method specifies asynchronous communication.
- getResponseHeader () – This method returns a string having a response Header of the HTTP objects.
The other methods are:
- send () – Helps to send the request.
- setRequestHeader(label, value) – It adds these two parameters to the HTTP header while sending.
XHR includes properties like Status and state, it has few status values like 0,1,2,3, and 4. The attributes of a state include 200 have are ok and 404 is page, not found-error.
The request is made like:
Var xh =new XMLHttpRequest ();xhr.open('GET', '/doc.file.php');
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status == 200) {
};
Xhr.send();
Here we are sending an image to the page in the browser without seeking data URIs.The request is made with ‘GET’.
Next, Uploading data through XHR.
Var xh=new XMLHttpRequest;
Xh=open(‘POST’, ‘upload’);
Examples
In this section, we shall test a few codes with several demos on JavaScript. Creating new HTTP requests and loading a few data.
Example #1
Code:
<!DOCTYPE html>
<html>
<body>
<h2> XMLHttpRequest Demo</h2>
<div id="sample">
<button type="button" onclick="functionreq()">Content demo</button>
</div>
<script>
function functionreq() {
var xht = new XMLHttpRequest();
xht.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 300) {
document.getElementById("sample").innerHTML =
this.responseText;
}
};
xht.open("GET", "welcome.txt", true);
xht.send();
}
</script>
</body>
</html>
Explanation:
The above code displays the status code if a page is not available.
Output:
Example #2
Code:
<form id='trial-form'>
first: <input name='first'><br>
Second: <input name='Second'><br>
<input type='submit'>
</form>
<script>
var tes1 = document.getElementById('trial-form');
tes1.onsubmit = function(event) {
event.preventDefault();
var req = new XMLHttpRequest();
req.open('POST', 'https://educba.com', /* async = */ false);
var fd = new FormData(document.getElementById('trial-form'));
req.send(fd);
console.log(req.response);
}
</script>
Explanation:
Here target URL performs access by sending the POST method. the above code uses two input buttons to take a value and waits for a response from a server. The output looks like this showing a form Data
Output:
Example #3
Code:
<!DOCTYPE html>
<html>
<head>
<title>Showing Computer IP Address</title>
<style>
body {
background-color: Brown;
}
h1 {
font-family: Arial;
text-align: center;
padding-top: 120px;
font-size: 50px;
margin: -12px;
}
p {
font-family: Algerian;
color: Orange;
text-align: center;
}
</style>
</head>
<body>
<h1 id=ipadd></h1>
<p>( Hi, this is your Current IP address)</p>
<script>
fetch("https://ipinfo.io/json")
.then(function (response) {
return response.json();
})
.then(function (myJson) {
document.querySelector("#ipadd").innerHTML = myJson.ip;
})
.catch(function (err) {
console.log("Error: " + err);
});
</script>
</body>
</html>
Explanation:
The above code snippets print the IP address of the state with addEventListener.
Output:
Example #4
Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="lib.js"></script>
<script type="text/javascript">
function process Start() {
if (window.XMLHttpRequest) {
var xmlh = new XMLHttpRequest();
document.getElementById("Content Type").innerHTML =
"<h1>Demo XMLHttpRequest Object</h1>";
} else {
var xmlh = false;
document.getElementById("Content Type").innerHTML =
"<h1>XMLHttp cannot be loaded!</h1>";
}
}
observeEvent(window, "load", function() {
var but = document.getElementById("btnStart");
observeEvent(but, "click", start);
});
</script>
<title>XMLHttpRequest using methods</title>
</head>
<body>
<button id="btnStart">process</button>
<div id="Content type"></div>
</body>
</html>
Explanation:
The above code generates an Http object. With the help of a Constructor, it generates an Object. If a page is succeded it generates the body content. If it fails it produces ‘Http cannot be loaded’.
Output:
Example #5
Code:
<html>
<body>
<span id="http header"></span>
<script type="text/javascript">
xmlh=null;
if (window.XMLHttpRequest)
{
xmlh=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xmlh=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlh!=null)
{
xmlh.onreadystatechange = function()
{
if(xmlh.readyState == 4)
{
a=xmlh.getResponseHeader("Content");
document.getElementById("header section").innerHTML=a;
}
}
xmlh.open("GET", "note.xml", true);
xmlh.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
</script>
</body>
</html
Explanation:
XHR fires state like unsent, opened, loading, and done. The above code takes the older Browser version to print their status code.
Output:
Conclusion
Doing a few codes with HTTP requests is very simple these days with the new browsers. The data which we request for a page returned with a piece of information is often done with the request get process. This article focuses on the XMLHTTP Request and fetches approaches. The two common uses include form submission and retrieving content.
Recommended Articles
This is a guide to XML HttpRequest. Here we discuss the How does HttpRequest Method work in XML? with examples and its code implementation. You may also have a look at the following articles to learn more –