XMLHttpRequest (XHR) is an
API
An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build ...
in the form of a
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
object whose
methods transmit
HTTP
HTTP (Hypertext Transfer Protocol) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, wher ...
requests from a
web browser
A web browser, often shortened to browser, is an application for accessing websites. When a user requests a web page from a particular website, the browser retrieves its files from a web server and then displays the page on the user's scr ...
to a
web server
A web server is computer software and underlying Computer hardware, hardware that accepts requests via Hypertext Transfer Protocol, HTTP (the network protocol created to distribute web content) or its secure variant HTTPS. A user agent, co ...
.
The methods allow a browser-based application to send requests to the server after page loading is complete, and receive information back.
XMLHttpRequest is a component of
Ajax programming. Prior to Ajax,
hyperlink
In computing, a hyperlink, or simply a link, is a digital reference providing direct access to Data (computing), data by a user (computing), user's point and click, clicking or touchscreen, tapping. A hyperlink points to a whole document or to ...
s and
form submissions were the primary mechanisms for interacting with the server, often replacing the current page with another one.
History
The concept behind XMLHttpRequest was conceived in 2000 by the developers of
Microsoft Outlook
Microsoft Outlook is a personal information manager software system from Microsoft, available as a part of the Microsoft 365 software suites. Primarily popular as an email client for businesses, Outlook also includes functions such as Calendari ...
.
The concept was then implemented within the
Internet Explorer 5 browser (1999). However, the original
syntax
In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
did not use the
XMLHttpRequest
identifier
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, person, physical countable object (or class thereof), or physical mass ...
. Instead, the developers used the identifiers
ActiveXObject("Msxml2.XMLHTTP")
and
ActiveXObject("Microsoft.XMLHTTP")
.
As of
Internet Explorer 7
Windows Internet Explorer 7 (IE7) (codenamed Rincon) is a version of Internet Explorer, a web browser for Windows. It was released by Microsoft on October 18, 2006. It was the first major update to the browser since 2001. It does not support ve ...
(2006), all browsers support the
XMLHttpRequest
identifier.
The
XMLHttpRequest
identifier is now the
''de facto'' standard in all the major browsers, including
Mozilla's Gecko layout engine (2002),
Safari
A safari (; originally ) is an overland journey to observe wildlife, wild animals, especially in East Africa. The so-called big five game, "Big Five" game animals of Africa – lion, African leopard, leopard, rhinoceros, African elephant, elep ...
1.2 (2004) and
Opera
Opera is a form of History of theatre#European theatre, Western theatre in which music is a fundamental component and dramatic roles are taken by Singing, singers. Such a "work" (the literal translation of the Italian word "opera") is typically ...
8.0 (2005).
Standards
The
World Wide Web Consortium
The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. Founded in 1994 by Tim Berners-Lee, the consortium is made up of member organizations that maintain full-time staff working together in ...
(W3C) published a ''Working Draft'' specification for the ''XMLHttpRequest'' object on April 5, 2006. On February 25, 2008, the W3C published the ''Working Draft Level 2'' specification.
Level 2 added methods to monitor event progress, allow cross-site requests, and handle byte streams. At the end of 2011, the Level 2 specification was absorbed into the original specification.
At the end of 2012, the
WHATWG
The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple Inc., the Mozilla Foundation and Opera Software, ...
took over development and maintains a
living document using
Web IDL
Web IDL is an interface description language (IDL) format for describing APIs (application programming interfaces) that are intended to be implemented in web browsers. Its adoption was motivated by the desire to improve the interoperability of ...
.
Usage
Generally, sending a request with XMLHttpRequest has several programming steps.
# Create an XMLHttpRequest object by calling a
constructor:
const request = new XMLHttpRequest();
# Call the "open" method to specify the request type, identify the relevant resource, and select synchronous or asynchronous operation:
request.open('GET', '/api/message', true /* asynchronous */);
# For an asynchronous request, set a listener that will be notified when the request's state changes:
request.onreadystatechange = listener;
# Initiate the request by calling the "send" method:
request.send();
# Respond to state changes in the event listener. If the server sends response data, by default it is captured in the "responseText" property. When the object stops processing the response, it changes to state 4, the "done" state.
function listener()
Aside from these general steps, XMLHttpRequest has many options to control how the request is sent and how the response is processed. Custom
header fields can be added to the request to indicate how the server should fulfill it, and data can be uploaded to the server by providing it in the "send" call. The response can be parsed from the
JSON
JSON (JavaScript Object Notation, pronounced or ) is an open standard file format and electronic data interchange, data interchange format that uses Human-readable medium and data, human-readable text to store and transmit data objects consi ...
format into a readily usable JavaScript object, or processed gradually as it arrives rather than waiting for the entire text. The request can be aborted prematurely or set to fail if not completed in a specified amount of time.
Cross-domain requests
In the early development of the
World Wide Web
The World Wide Web (WWW or simply the Web) is an information system that enables Content (media), content sharing over the Internet through user-friendly ways meant to appeal to users beyond Information technology, IT specialists and hobbyis ...
, it was found possible to breach users' security by the use of JavaScript to exchange information from one web site with that from another less reputable one. All modern browsers therefore implement a
same origin policy that prevents many such attacks, such as
cross-site scripting. XMLHttpRequest data is subject to this security policy, but sometimes web developers want to intentionally circumvent its restrictions. This is sometimes due to the legitimate use of subdomains as, for example, making an XMLHttpRequest from a page created by
foo.example.com
for information from
bar.example.com
will normally fail.
Various alternatives exist to circumvent this security feature, including using
JSONP,
Cross-Origin Resource Sharing (CORS) or alternatives with plugins such as
Flash or
Silverlight (both now deprecated). Cross-origin XMLHttpRequest is specified in W3C's XMLHttpRequest Level 2 specification. Internet Explorer did not implement CORS until version 10. The two previous versions (8 and 9) offered similar functionality through the XDomainRequest (XDR) API. CORS is now supported by all modern browsers (desktop and mobile).
The CORS protocol has several restrictions, with two models of support. The ''simple'' model does not allow setting custom request headers and omits
cookies. Further, only the HEAD, GET and POST
request methods are supported, and POST only allows the following
MIME
A mime artist, or simply mime (from Greek language, Greek , , "imitator, actor"), is a person who uses ''mime'' (also called ''pantomime'' outside of Britain), the acting out of a story through body motions without the use of speech, as a the ...
types: "text/plain", "application/x-www-urlencoded" and "
multipart/form-data". Only "text/plain" was initially supported. The other model detects when one of the ''non-simple'' features are requested and sends a ''pre-flight request'' to the server to negotiate the feature.
Fetch alternative
Program flow using asynchronous XHR callbacks can present difficulty with readability and maintenance.
ECMAScript
ECMAScript (; ES) is a standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is stan ...
2015 (ES6) added the
promise construct to simplify asynchronous logic. Browsers have since implemented the alternative
fetch()
interface to achieve the same functionality as XHR using
promises instead of callbacks.
Fetch is also standardized by WHATWG.
Example
fetch('/api/message')
.then(response => )
.then(text => );
See also
*
WebSocket
*
Representational state transfer
REST (Representational State Transfer) is a software architectural style that was created to describe the design and guide the development of the architecture for the World Wide Web. REST defines a set of constraints for how the architecture of ...
(REST)
References
Notes
External links
XMLHttpRequest Living Standardby the
WHATWG
The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple Inc., the Mozilla Foundation and Opera Software, ...
XMLHttpRequest Level 1draft by the
W3C
The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. Founded in 1994 by Tim Berners-Lee, the consortium is made up of member organizations that maintain full-time staff working together in ...
{{DEFAULTSORT:Xmlhttprequest
XML
Microsoft application programming interfaces
Microsoft initiatives
JavaScript
Hypertext Transfer Protocol clients
Ajax (programming)
Articles with example JavaScript code
Web standards
2000 software