Categories

Sep 17, 2019 in React JS

Q: What is XMLHttpRequest Object in Ajax?

1 Answer

Sep 17, 2019

XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. 

XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript.Despite of having the word “XML” in its name, it can operate on any data, not only in XML format. We can upload/download files, track progress and much more.

In modern web-development XMLHttpRequest is used for three reasons:

1. Historical reasons: we need to support existing scripts with XMLHttpRequest.

2. We need to support old browsers, and don’t want polyfills (e.g. to keep scripts tiny).

3. We need something that fetch can’t do yet, e.g. to track upload progress.

XMLHttpRequest has two modes of operation: synchronous and asynchronous.

Let’s see the asynchronous first, as it’s used in the majority of cases.

To do the request, we need 3 steps:

1.Create XMLHttpRequest:

let xObj = new XMLHttpRequest();

2. Initialize it:

xObj.open(method, URL, [async, user, password])

This method is usually called right after new XMLHttpRequest. It specifies the main parameters of the request:

method – HTTP-method. Usually "GET" or "POST".

URL – the URL to request, a string, can be URL object.

async – if explicitly set to false, then the request is synchronous, we’ll cover that a bit later.

user, password – login and password for basic HTTP auth (if required).

3. Send it out.This method opens the connection and sends the request to server. The optional body parameter contains the request body.

xObj.send([body])

4. Listen to xObj events for response.

These three are the most widely used:

load – when the result is ready, that includes HTTP errors like 404.

error – when the request couldn’t be made, e.g. network down or invalid URL.

progress – triggers periodically during the download, reports how much downloaded.

xObj.onload = function() {

  alert(`Loaded: ${xObj.status} ${xObj.response}`);

};

xObj.onerror = function() { // only triggers if the request couldn't be made at all

  alert(`Network Error`);

};

xObj.onprogress = function(event) { // triggers periodically

  // event.loaded - how many bytes downloaded

  // event.lengthComputable = true if the server sent Content-Length header

  // event.total - total number of bytes (if lengthComputable)

  alert(`Received ${event.loaded} of ${event.total}`);

};

Click here to read more about React JS
Click here to read more about Insurance

Related questions

Madanswer
Jun 26 in React JS
Jun 19 in React JS
Jun 19 in React JS
...