bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

AJAX - The XMLHttpRequest Object

The keystone of AJAX is the XMLHttpRequest object.

  • Create an XMLHttpRequest object
  • Define a callback function
  • Open the XMLHttpRequest object
  • Send a Request to a server

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

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

Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object

variable
= new XMLHttpRequest();

Define a Callback Function

A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the response is ready.

xhttp.onload = function() {
 // What to do when the response is ready
}

Send a Request

To send a request to a server, you can use the open() and send() methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Example

// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function xhttp.onload = function() { // Here you can use the Data
}
// Send a request xhttp.open("GET", "ajax_info.txt"); xhttp.send();

Access Across Domains

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

This means that both the web page and the XML file it tries to load, must be located on the same server.

If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

XMLHttpRequest Object Methods

MethodDescription
new XMLHttpRequest()Creates a new XMLHttpRequest object
abort()Cancels the current request
getAllResponseHeaders()Returns header information
getResponseHeader()Returns specific header information
open( method, url, async, user, psw )Specifies the request method : the request type GET or POST url : the file location async : true (asynchronous) or false (synchronous) user : optional user name psw : optional password
send()Sends the request to the server Used for GET requests
send( string )Sends the request to the server. Used for POST requests
setRequestHeader()Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

PropertyDescription
onloadDefines a function to be called when the request is received (loaded)
onreadystatechangeDefines a function to be called when the readyState property changes
readyStateHolds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
responseTextReturns the response data as a string
responseXMLReturns the response data as XML data
statusReturns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference
statusTextReturns the status-text (e.g. "OK" or "Not Found")

The onload Property

With the XMLHttpRequest object you can define a callback function to be executed when the request receives an answer.

The function is defined in the onload property of the XMLHttpRequest object:

Example

xhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Multiple Callback Functions

If you have more than one AJAX task in a website, you should create one function for executing the XMLHttpRequest object, and one callback function for each AJAX task.

The function call should contain the URL and what function to call when the response is ready.

Example

loadDoc(" url-1 ", myFunction1);
loadDoc(" url-2 ", myFunction2);
function loadDoc(url, cFunction) {
 const xhttp = new XMLHttpRequest();
 xhttp.onload = function() {cFunction(this);}
 xhttp.open("GET", url);
 xhttp.send();
}
function myFunction1(xhttp) {
 // action goes here
}
function myFunction2(xhttp) {
 // action goes here
}

The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a callback function to be executed when the readyState changes.

The status property and the statusText properties hold the status of the XMLHttpRequest object.

PropertyDescription
onreadystatechangeDefines a function to be called when the readyState property changes
readyStateHolds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
status200: "OK" 403: "Forbidden" 404: "Page not found" For a complete list go to the Http Messages Reference
statusTextReturns the status-text (e.g. "OK" or "Not Found")

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example

function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.

Previous

AJAX Introduction

Next

AJAX - XMLHttpRequest

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

The XMLHttpRequest ObjectCreate an XMLHttpRequest ObjectDefine a Callback FunctionSend a RequestAccess Across DomainsXMLHttpRequest Object MethodsXMLHttpRequest Object PropertiesThe onload PropertyMultiple Callback FunctionsThe onreadystatechange Property