JavaScript XMLHttpRequest Object

JavaScript XMLHttpRequest Object

The XMLHttpRequest (XHR) objects is a core of Ajax used to interact with servers. This helps you to retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without reloading the whole page.

Note: Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

Requesting a URL

In the following example, we request a URL and receive a response.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JavaScript xmlHttpRequest()</h1> <button onclick="myFunction()">Click Me</button> <script> function myFunction() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; xhttp.open("GET", "/greet.php", true); xhttp.send(); } </script> </body> </html>

Syntax

var xhttp = new XMLHttpRequest();

XMLHttpRequest Object Methods

ValueExplanation
abort()Terminate the current request.
getAllResponseHeaders()Returns all the response headers
getResponseHeader()Returns the string containing the text of a particular header's value.
new XMLHttpRequest()Creates a new XMLHttpRequest.
open(method,url,async,user,pass)Initializes a newly-created request, or re-initializes an existing one.
Parameters Explanation
  • method - Required. Specifies the request type 'GET' or 'POST'
  • url - Required. Specifies the url to which the request is sent.
  • async - Required. true (asynchronous) or false (synchronous). Default is true.
  • user - Optional. user name for authentication in server side.
  • pass - Optional. password for authentication in server side.
send(data)sends the request to the server.
setRequestHeader()Sets the value of an HTTP request header.

XMLHttpRequest Object Properties

ValueExplanation
onreadystatechangeSpecifies a function which is called from the user interface thread.
readyStateReturns the state an XMLHttpRequest client is in.
Possible values are
  • 0 - UNSENT
  • 1 - OPENED
  • 2 - HEADERS_RECEIVED
  • 3 - LOADING
  • 4 - DONE
responseTextReturns the text received from a server following a request being sent.
responseXMLReturns a Document containing the HTML or XML retrieved by the request.
statusReturns the numerical HTTP status code of the XMLHttpRequest's response.
statusTextReturns a DOMString containing the response's status message as returned by the HTTP server.

Cross-origin resource sharing

For security reasons, browsers do not allow access across domains.

For example: From www.abc.com you can't send XMLHttpRequest to www.xyz.com.

All resources of www.abc.com can only be accessed by itself.

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author