EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials XML Tutorial XML HttpRequest 
Secondary Sidebar
XML Tutorial
  • Basic
    • What is XML?
    • XML Tags
    • XML URL
    • XPath Sibling
    • XML root element
    • XML Encryption
    • XML Parsing php
    • xml parsing with java
    • Dataset XML
    • XML Parser in C#
    • XML Tree
    • XML boolean
    • XML sitemap
    • XML Array
    • XML reserved characters
    • XML Viewer
    • XML Uses
    • XML Special Characters
    • XML generator
    • XML file format
    • XML DOM
    • XML ampersand
    • XML Mapping
    • XML File
    • XML Element
    • XML HttpRequest
    • XML XSD
    • XML Schema
    • XML Namespaces
    • XML Comments
    • XML Attributes
    • XML Encoding
    • XML Validation
    • XML CDATA
    • XML Database
    • XML Technologies
    • XML Error
    • XML DTD
    • XML Date
    • XML Parsers
    • String in XML
    • XML with CSS
    • XML Versions
    • XML Features
    • XML Commands
    • Servlet web.xml
    • XPath Injection
    • XPath Functions
    • XPath starts-with
    • XPath Selector
    • XPath Count
    • XPath XML
    • XML Parsing in Oracle
    • XML parsing in python
  • Xpath
    • What is XPath?
    • XPath namespace
    • XPath for JSON
    • XPath Last Element
    • Xpath Substring
    • XPath First Element
    • XPath local-name
    • XPath Multiple Attributes
    • XPath Matches
    • XPath Position
    • XPath Index
    • XPath regex
    • XPath id contains
    • XPath innertext
    • XPath Multiple Conditions
    • XPath Helper
    • XPath Generator
    • XPath ID
    • XPath Locator

XML HttpRequest 

By Priya PedamkarPriya Pedamkar

XML HttpRequest

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

A simple syntax looks like b creating a constructor

Var xmlh=new XMLHttpRequest ();

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,883 ratings)

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:

  1. 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:

XML HttpRequest 1

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:

XML HttpRequest 2

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 3

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 4

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:

example 5

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 –

  1. XML Element
  2. XML XSD
  3. XML Namespaces
  4. XML Comments
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more