HOME

TheInfoList



OR:

XMLHttpRequest (XHR) is an API in the form of an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
whose
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
transfer data between a
web browser A web browser is application software 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 screen. Browsers are used o ...
and a
web server A web server is computer software and underlying hardware that accepts requests via HTTP (the network protocol created to distribute web content) or its secure variant HTTPS. A user agent, commonly a web browser or web crawler, initia ...
. The object is provided by the browser's
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
environment. Particularly, retrieval of data from XHR for the purpose of continually modifying a loaded web page is the underlying concept of
Ajax Ajax may refer to: Greek mythology and tragedy * Ajax the Great, a Greek mythological hero, son of King Telamon and Periboea * Ajax the Lesser, a Greek mythological hero, son of Oileus, the king of Locris * ''Ajax'' (play), by the ancient Gree ...
design. Despite the name, XHR can be used with protocols other than
HTTP The Hypertext Transfer Protocol (HTTP) 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 We ...
and data can be in the form of not only
XML Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. T ...
, but also
JSON JSON (JavaScript Object Notation, pronounced ; also ) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other se ...
,
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaS ...
or
plain text In computing, plain text is a loose term for data (e.g. file contents) that represent only characters of readable material but not its graphical representation nor other objects (floating-point numbers, images, etc.). It may also include a limit ...
.
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, l ...
maintains an XHR standard as a living document. Ongoing work at the W3C to create a stable specification is based on snapshots of the WHATWG standard.


History

The concept behind the ''XMLHttpRequest'' object was originally created by the developers of Outlook Web Access (by Microsoft) for Microsoft Exchange Server 2000. An
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
called ''IXMLHTTPRequest'' was developed and implemented into the second version of the MSXML library using this concept. The second version of the MSXML library was shipped with
Internet Explorer 5.0 Microsoft Internet Explorer 5 (IE5) is a graphical web browser, the fifth version of Internet Explorer, the successor to Internet Explorer 4 and one of the main participants of the first browser war. Its distribution methods and Windows integ ...
in March 1999, allowing access, via
ActiveX ActiveX is a deprecated software framework created by Microsoft that adapts its earlier Component Object Model (COM) and Object Linking and Embedding (OLE) technologies for content downloaded from a network, particularly from the World Wide We ...
, to the ''IXMLHTTPRequest'' interface using the ''XMLHTTP'' wrapper of the MSXML library. Internet Explorer versions 5 and 6 did not define the XMLHttpRequest object identifier in their scripting languages as the XMLHttpRequest identifier itself was not standard at the time of their releases.
Backward compatibility Backward compatibility (sometimes known as backwards compatibility) is a property of an operating system, product, or technology that allows for interoperability with an older legacy system, or with input designed for such a system, especiall ...
can be achieved through object detection if the XMLHttpRequest identifier does not exist. Microsoft added the ''XMLHttpRequest'' object identifier to its scripting languages in
Internet Explorer 7.0 Windows Internet Explorer 7 (IE7) (codenamed Rincon) is a web browser for Windows. It was released by Microsoft on October 18, 2006, as the seventh version of Internet Explorer and the successor to Internet Explorer 6. Internet Explorer 7 is par ...
released in October 2006. The
Mozilla Mozilla (stylized as moz://a) is a free software community founded in 1998 by members of Netscape. The Mozilla community uses, develops, spreads and supports Mozilla products, thereby promoting exclusively free software and open standards, ...
project developed and implemented an interface called ''nsIXMLHttpRequest'' into the
Gecko Geckos are small, mostly carnivorous lizards that have a wide distribution, found on every continent except Antarctica. Belonging to the infraorder Gekkota, geckos are found in warm climates throughout the world. They range from . Geckos a ...
layout engine. This interface was modeled to work as closely to Microsoft's ''IXMLHTTPRequest'' interface as possible. Mozilla created a wrapper to use this interface through a JavaScript object which they called ''XMLHttpRequest''. The ''XMLHttpRequest'' object was accessible as early as Gecko version 0.6 released on December 6, 2000, but it was not completely functional until as late as version 1.0 of Gecko released on June 5, 2002. The ''XMLHttpRequest'' object became a ''de facto'' standard in other major web clients, implemented in
Safari A safari (; ) is an overland journey to observe wild animals, especially in eastern or southern Africa. The so-called "Big Five" game animals of Africa – lion, leopard, rhinoceros, elephant, and Cape buffalo – particularly form an impor ...
1.2 released in February 2004,
Konqueror Konqueror is a free and open-source web browser and file manager that provides web access and file-viewer functionality for file systems (such as local files, files on a remote FTP server and files in a disk image). It forms a core part of t ...
,
Opera Opera is a form of theatre in which music is a fundamental component and dramatic roles are taken by singers. Such a "work" (the literal translation of the Italian word "opera") is typically a collaboration between a composer and a libr ...
8.0 released in April 2005, and
iCab iCab is a web browser for Mac OS by Alexander Clauss, derived from Crystal Atari Browser (CAB) for Atari TOS compatible computers. It was one of the few browsers still updated for the classic Mac OS prior to that version being discontinued afte ...
3.0b352 released in September 2005. With the advent of cross-browser JavaScript libraries such as
jQuery jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License. As of Aug 2022, jQuery is u ...
, developers can invoke XMLHttpRequest functionality indirectly.


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 and led by Tim Berners-Lee, the consortium is made up of member organizations that maintain full-time staff working ...
published a ''Working Draft'' specification for the ''XMLHttpRequest'' object on April 5, 2006,
edited Editing is the process of selecting and preparing written, photographic, visual, audible, or cinematic material used by a person or an entity to convey a message or information. The editing process can involve correction, condensation, org ...
by Anne van Kesteren of
Opera Software Opera is a Norwegian multinational technology company and subsidiary of Kunlun that specializes in web browser development, fintech, as well as services such as Opera News and YoYo Games. The company's total user base, including users of it ...
and Dean Jackson of W3C. Its goal is "to document a minimum set of interoperable features based on existing implementations, allowing Web developers to use these features without platform-specific code." The W3C also published another ''Working Draft'' specification for the ''XMLHttpRequest'' object, "XMLHttpRequest Level 2", on February 25, 2008. Level 2 consists of extended functionality to the ''XMLHttpRequest'' object, including, but not limited to, progress events, support for cross-site requests, and the handling of byte streams. At the end of 2011, the Level 2 specification was abandoned and 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, l ...
took over development and maintains a living standard using
Web IDL Web IDL is an interface description language (IDL) format for describing application programming interfaces (APIs) that are intended to be implemented in web browsers. Its adoption was motivated by the desire to improve the interoperability of w ...
. W3C's current drafts are based on snapshots of 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, l ...
standard.


HTTP request

The following sections demonstrate how a request using the XMLHttpRequest object functions within a conforming user agent based on the W3C Working Draft. As the W3C standard for the XMLHttpRequest object is still a draft, user agents may not abide by all the functionings of the W3C definition and any of the following is subject to change. Extreme care should be taken into consideration when scripting with the XMLHttpRequest object across multiple user agents. This article will try to list the inconsistencies between the major user agents.


The ''open'' method

The
HTTP The Hypertext Transfer Protocol (HTTP) 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 We ...
and
HTTPS Hypertext Transfer Protocol Secure (HTTPS) is an extension of the Hypertext Transfer Protocol (HTTP). It is used for secure communication over a computer network, and is widely used on the Internet. In HTTPS, the communication protocol is enc ...
requests of the XMLHttpRequest object must be initialized through the ''open''
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
. This method must be invoked prior to the actual sending of a request to validate and resolve the request method, URL, and URI user information to be used for the request. This method does not assure that the URL exists or the user information is correct. This method can accept up to five
parameter A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
s, but requires only two, to initialize a request. open( Method, URL, Asynchronous, UserName, Password ) The first parameter of the method is a
text string In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). ...
indicating the HTTP request method to use. The request methods that must be supported by a conforming
user agent In computing, a user agent is any software, acting on behalf of a user, which "retrieves, renders and facilitates end-user interaction with Web content". A user agent is therefore a special kind of software agent. Some prominent examples of us ...
, defined by the W3C draft for the XMLHttpRequest object, are currently listed as the following. * GET (supported by
Internet Explorer 7 Windows Internet Explorer 7 (IE7) (codenamed Rincon) is a web browser for Windows. It was released by Microsoft on October 18, 2006, as the seventh version of Internet Explorer and the successor to Internet Explorer 6. Internet Explorer 7 is pa ...
+, Mozilla 1+) * POST (supported by IE7+, Mozilla 1+) * HEAD (supported by IE7+) * PUT * DELETE * OPTIONS (supported by IE7+) However, request methods are not limited to the ones listed above. The W3C draft states that a browser may support additional request methods at their own discretion. The second parameter of the method is another
text string In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). ...
, this one indicating the URL of the HTTP request. The W3C recommends that browsers should raise an error and not allow the request of a URL with either a different
port A port is a maritime facility comprising one or more wharves or loading areas, where ships load and discharge cargo and passengers. Although usually situated on a sea coast or estuary, ports can also be found far inland, such as H ...
or ''ihost'' URI component from the current document. The third parameter, a boolean value indicating whether or not the request will be asynchronous, is not a required parameter by the W3C draft. The default value of this parameter should be assumed to be true by a W3C conforming user agent if it is not provided. An asynchronous request ("true") will not wait on a server response before continuing with the execution of the current script. It will instead invoke the onreadystatechange
event listener In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggere ...
of the XMLHttpRequest object throughout the various stages of the request. A synchronous request ("false") however will block execution of the current script until the request has been completed, thus not invoking the ''onreadystatechange'' event listener. Note that starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), Blink 39.0 (Chrome), and Edge 13, synchronous requests on the main thread have been deprecated due to their negative impact on the user experience as they will cause freezing of the UI while the thread performs the request. The fourth and fifth parameters are the
user Ancient Egyptian roles * User (ancient Egyptian official), an ancient Egyptian nomarch (governor) of the Eighth Dynasty * Useramen, an ancient Egyptian vizier also called "User" Other uses * User (computing), a person (or software) using an ...
name and
password A password, sometimes called a passcode (for example in Apple devices), is secret data, typically a string of characters, usually used to confirm a user's identity. Traditionally, passwords were expected to be memorized, but the large number of ...
, respectively. These parameters, or just the username, may be provided for authentication and authorization if required by the server for this request. var xmlhttp; if (window.XMLHttpRequest)


The ''setRequestHeader'' method

Upon successful initialization of a request, the ''setRequestHeader'' method of the XMLHttpRequest object can be invoked to send
HTTP header The Hypertext Transfer Protocol (HTTP) 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, w ...
s with the request. setRequestHeader( Name, Value ) The first parameter of this method is the text string name of the header. The second parameter is the text string value. This method must be invoked for each header that needs to be sent with the request. Any headers attached here will be removed the next time the ''open'' method is invoked in a W3C conforming user agent.


The ''send'' method

To send an HTTP request, the ''send'' method of the XMLHttpRequest must be invoked. This method accepts a single parameter containing the content to be sent with the request. send( Data ) This parameter may be omitted if no content needs to be sent. The W3C draft states that this parameter may be any type available to the scripting language as long as it can be turned into a text string, with the exception of the DOM ''document'' object. If a user agent cannot serialise the parameter, then the parameter should be ignored. Firefox 3.0.x and previous versions will however throw an exception if send is called without an argument. If the parameter is a DOM ''document'' object, a user agent should assure the document is turned into well-formed XML using the encoding indicated by the ''inputEncoding'' property of the ''document'' object. If the Content-Type request header was not added through ''setRequestHeader'' yet, it should automatically be added by a conforming user agent as "application/xml;charset=''charset''," where ''charset'' is the encoding used to encode the document. If the user agent is configured to use a
proxy server In computer networking, a proxy server is a server application that acts as an intermediary between a client requesting a resource and the server providing that resource. Instead of connecting directly to a server that can fulfill a reques ...
, then the XMLHttpRequest object will modify the request appropriately so as to connect to the proxy instead of the origin server, and send Proxy-Authorization headers as configured.


The ''onreadystatechange'' event listener

If the open method of the XMLHttpRequest object was invoked with the third parameter set to ''true'' for an asynchronous request, the onreadystatechange event listener will be automatically invoked for each of the following actions that change the readyState property of the XMLHttpRequest object. State changes work like this: * State Description 0 The request is not initialized. 1 The request has been set up. 2 The request has been sent. 3 The request is in process. 4 The request is completed. * After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1 (OPENED). * After the send method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object should be assigned a value of 2 (HEADERS_RECEIVED). * Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3 (LOADING). * Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4 (DONE). The listener will only respond to state changes which occur after the listener is defined. To detect states 1 and 2, the listener must be defined before the open method is invoked. The open method must be invoked before the send method is invoked. var request = new XMLHttpRequest(); request.onreadystatechange = function () ; request.open('GET', 'somepage.xml', true); request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // Tells server that this call is made for ajax purposes. // Most libraries like jQuery/Prototype/Dojo do this request.send(null); // No data needs to be sent along with the request.


The HTTP response

After a successful and completed call to the send method of the XMLHttpRequest, if the server response was well-formed XML and the ''Content-Type'' header sent by the server is understood by the user agent as an
Internet media type A media type (also known as a MIME type) is a two-part identifier for file formats and format contents transmitted on the Internet. The Internet Assigned Numbers Authority (IANA) is the official authority for the standardization and publication o ...
for XML, the ''responseXML'' property of the XMLHttpRequest object will contain a DOM document object. Another property, ''responseText'' will contain the response of the server in plain text by a conforming user agent, regardless of whether or not it was understood as XML.


Cross-domain requests

In the early development of the
World Wide Web The World Wide Web (WWW), commonly known as the Web, is an information system enabling documents and other web resources to be accessed over the Internet. Documents and downloadable media are made available to the network through web ...
, 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 Same may refer to: *Sameness or identity Places * Same (Homer), an island mentioned by Homer in the ''Odyssey'' * Same (polis), an ancient city * Same, East Timor, the capital of the Manufahi district * Samé, Mali * Same, Tanzania * Same Distric ...
that prevents many such attacks, such as
cross-site scripting Cross-site scripting (XSS) is a type of security vulnerability that can be found in some web applications. XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability m ...
. 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 JSONP, or JSON-P (JSON with Padding), is a historical JavaScript technique for requesting data by loading a element, which is an element intended to load ordinary JavaScript. It was proposed by Bob Ippolito in 2005. JSONP enables sharing of data b ...
,
Cross-Origin Resource Sharing Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, ...
(CORS) or alternatives with plugins such as Flash or
Silverlight Microsoft Silverlight is a discontinued application framework designed for writing and running rich web applications, similar to Adobe's runtime, Adobe Flash. A plugin for Silverlight is still available for a very small number of browsers. Whi ...
(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 A cookie is a baked or cooked snack or dessert that is typically small, flat and sweet. It usually contains flour, sugar, egg, and some type of oil, fat, or butter. It may include other ingredients such as raisins, oats, chocolate chi ...
. Further, only the HEAD, GET and POST request methods are supported, and POST only allows the following
MIME Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email messages to support text in character sets other than ASCII, as well as attachments of audio, video, images, and application programs. Message ...
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 JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripti ...
2015 (ES6) added the
promise A promise is a commitment by someone to do or not do something. As a noun ''promise'' means a declaration assuring that one will or will not do something. As a verb it means to commit oneself by a promise to do or give. It can also mean a capacity ...
construct to simplify asynchronous logic. Browsers have since implemented the alternative fetch() interface to achieve the same functionality as XHR using
promises A promise is a transaction whereby a person makes a vow or the suggestion of a guarantee. Promise(s) may also refer to: Places * Promise, Oregon * Promise, South Dakota * Promise City, Iowa * Promise Land, Tennessee or Promise Film and TV * '' ...
instead of callbacks. Fetch is also standardized by WHATWG.


Example

fetch("somepage.xml", ).then((response) => );


See also

*
WebSocket WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as in 2011. The current API specification allowing web applications ...
* Representational state transfer (REST)


References


External links


XMLHttpRequest Living Standard
by 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, l ...

XMLHttpRequest Level 1
draft by the W3C {{DEFAULTSORT:Xmlhttprequest XML Microsoft application programming interfaces Microsoft initiatives JavaScript Hypertext Transfer Protocol clients Ajax (programming) Web standards Articles with example code 2000 software