XMLHttpRequest

Last updated

XMLHttpRequest (XHR) is an API in the form of a JavaScript object whose methods transmit HTTP requests from a web browser to a web server. [1] The methods allow a browser-based application to make a fine-grained server call and store the results in XMLHttpRequest's responseText attribute. [2] XMLHttpRequest is a component of Ajax programming. Prior to Ajax, hyperlinks and form submissions were the primary mechanisms for interacting with the server, often replacing the current page with another one. [2]

Contents

History

The concept behind XMLHttpRequest was conceived in 2000 by the developers of Microsoft Outlook. [3] The concept was then implemented within the Internet Explorer 5 browser (2001). However, the original syntax did not use the XMLHttpRequest identifier. Instead, the developers used the identifiers ActiveXObject("Msxml2.XMLHTTP") and ActiveXObject("Microsoft.XMLHTTP"). [4] As of Internet Explorer 7 (2006), all browsers support the XMLHttpRequest identifier. [4]

The XMLHttpRequest identifier is now the de facto standard in all the major browsers, including Mozilla's Gecko layout engine (2002), [5] Safari 1.2 (2004) and Opera 8.0 (2005). [6]

Standards

The World Wide Web Consortium (W3C) published a Working Draft specification for the XMLHttpRequest object on April 5, 2006. [7] [lower-alpha 1] On February 25, 2008, the W3C published the Working Draft Level 2 specification. [8] 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. [9]

At the end of 2012, the WHATWG took over development and maintains a living document using Web IDL. [10]

Usage

Generally, sending a request with XMLHttpRequest has several programming steps. [11]

  1. Create an XMLHttpRequest object by calling a constructor:
    varrequest=newXMLHttpRequest();
  2. Call the "open" method to specify the request type, identify the relevant resource, and select synchronous or asynchronous operation:
    request.open('GET','/api/products/12',true/* asynchronous */);
  3. Set an event listener that will be notified when the request's state changes:
    request.onreadystatechange=listener;
  4. Initiate the request by calling the "send" method:
    request.send();
  5. 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.
    functionlistener(){// Check whether the request is done and successful.if(request.readyState==4&&request.status==200)console.log(request.responseText);// Display the text.}

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, [12] and data can be uploaded to the server by providing it in the "send" call. [13] The response can be parsed from the JSON format into a readily usable JavaScript object, or processed gradually as it arrives rather than waiting for the entire text. [14] The request can be aborted prematurely [15] or set to fail if not completed in a specified amount of time. [16]

Cross-domain requests

In the early development of the World Wide 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 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. [17] 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). [18]

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 types: "text/plain", "application/x-www-urlencoded" and "multipart/form-data". Only "text/plain" was initially supported. [19] The other model detects when one of the non-simple features are requested and sends a pre-flight request [20] to the server to negotiate the feature.

Fetch alternative

Program flow using asynchronous XHR callbacks can present difficulty with readability and maintenance. ECMAScript 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. [21]

Example

fetch('/api/products/12').then(response=>{if(response.status!=200)thrownewError('Request failed');returnresponse.text();}).then(text=>{console.log(text);});

See also

Related Research Articles

<span class="mw-page-title-main">Document Object Model</span> Convention for representing and interacting with objects in HTML, XHTML, and XML documents

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an HTML or XML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document. Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.

Dynamic HTML, or DHTML, is a term which was used by some browser vendors to describe the combination of HTML, style sheets and client-side scripts that enabled the creation of interactive and animated documents. The application of DHTML was introduced by Microsoft with the release of Internet Explorer 4 in 1997.

<span class="mw-page-title-main">World Wide Web</span> Linked hypertext system on the Internet

The World Wide Web is an information system that enables content sharing over the Internet through user-friendly ways meant to appeal to users beyond IT specialists and hobbyists. It allows documents and other web resources to be accessed over the Internet according to specific rules of the Hypertext Transfer Protocol (HTTP).

XForms is an XML format used for collecting inputs from web forms. XForms was designed to be the next generation of HTML / XHTML forms, but is generic enough that it can also be used in a standalone manner or with presentation languages other than XHTML to describe a user interface and a set of common data manipulation tasks.

URL redirection, also called URL forwarding, is a World Wide Web technique for making a web page available under more than one URL address. When a web browser attempts to open a URL that has been redirected, a page with a different URL is opened. Similarly, domain redirection or domain forwarding is when all pages in a URL domain are redirected to a different domain, as when wikipedia.com and wikipedia.net are automatically redirected to wikipedia.org.

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML document, choosing the appearance of a page, or jumping to positions in multimedia content.

DOM Events are a signal that something has occurred, or is occurring, and can be triggered by user interactions or by the browser. Client-side scripting languages like JavaScript, JScript, VBScript, and Java can register various event handlers or listeners on the element nodes inside a DOM tree, such as in HTML, XHTML, XUL, and SVG documents.

Ajax is a set of web development techniques that uses various web technologies on the client-side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behaviour of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows web pages and, by extension, web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly utilize JSON instead of XML.

<span class="mw-page-title-main">Dynamic web page</span> Type of web page

A dynamic web page is a web page constructed at runtime, as opposed to a static web page, delivered as it is stored. A server-side dynamic web page is a web page whose construction is controlled by an application server processing server-side scripts. In server-side scripting, parameters determine how the assembly of every new web page proceeds, and including the setting up of more client-side processing. A client-side dynamic web page processes the web page using JavaScript running in the browser as it loads. JavaScript can interact with the page via Document Object Model (DOM), to query page state and modify it. Even though a web page can be dynamic on the client-side, it can still be hosted on a static hosting service such as GitHub Pages or Amazon S3 as long as there is not any server-side code included.

A webform, web form or HTML form on a web page allows a user to enter data that is sent to a server for processing. Forms can resemble paper or database forms because web users fill out the forms using checkboxes, radio buttons, or text fields. For example, forms can be used to enter shipping or credit card data to order a product, or can be used to retrieve search results from a search engine.

Remote scripting is a technology which allows scripts and programs that are running inside a browser to exchange information with a server. The local scripts can invoke scripts on the remote side and process the returned information.

Comet is a web application model in which a long-held HTTPS request allows a web server to push data to a browser, without the browser explicitly requesting it. Comet is an umbrella term, encompassing multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins. The Comet approach differs from the original model of the web, in which a browser requests a complete web page at a time.

The Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson in February 2005 as part of Ajax support in Ruby on Rails. It is implemented as a single file of JavaScript code, usually named prototype.js. Prototype is distributed standalone, but also as part of larger projects, such as Ruby on Rails, script.aculo.us and Rico. As of March 2021, according to w3techs, Prototype is used by 0.6% of all websites.

A file inclusion vulnerability is a type of web vulnerability that is most commonly found to affect web applications that rely on a scripting run time. This issue is caused when an application builds a path to executable code using an attacker-controlled variable in a way that allows the attacker to control which file is executed at run time. A file include vulnerability is distinct from a generic directory traversal attack, in that directory traversal is a way of gaining unauthorized file system access, and a file inclusion vulnerability subverts how an application loads code for execution. Successful exploitation of a file inclusion vulnerability will result in remote code execution on the web server that runs the affected web application. An attacker can use remote code execution to create a web shell on the web server, which can be used for website defacement.

JSONP, or JSON-P, is a historical JavaScript technique for requesting data by loading a <script> element, which is an element intended to load ordinary JavaScript. It was proposed by Bob Ippolito in 2005. JSONP enables sharing of data bypassing same-origin policy, which disallows running JavaScript code to read media DOM elements or XMLHttpRequest data fetched from outside the page's originating site. The originating site is indicated by a combination of URI scheme, hostname, and port number.

A single-page application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current web page with new data from the web server, instead of the default method of a web browser loading entire new pages. The goal is faster transitions that make the website feel more like a native app.

Cross-origin resource sharing (CORS) is a mechanism that allows a web page to access restricted resources from a server on a domain different than the domain that served the web page.

Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website or web application where unauthorized commands are submitted from a user that the web application trusts. There are many ways in which a malicious website can transmit such commands; specially-crafted image tags, hidden forms, and JavaScript fetch or XMLHttpRequests, for example, can all work without the user's interaction or even knowledge. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser. In a CSRF attack, an innocent end user is tricked by an attacker into submitting a web request that they did not intend. This may cause actions to be performed on the website that can include inadvertent client or server data leakage, change of session state, or manipulation of an end user's account.

HtmlUnit is a headless web browser written in Java. It allows high-level manipulation of websites from other Java code, including filling and submitting forms and clicking hyperlinks. It also provides access to the structure and the details within received web pages. HtmlUnit emulates parts of browser behaviour including the lower-level aspects of TCP/IP and HTTP. A sequence such as getPage(url), getLinkWith("Click here"), click allows a user to navigate through hypertext and obtain web pages that include HTML, JavaScript, Ajax and cookies. This headless browser can deal with HTTPS security, basic HTTP authentication, automatic page redirection and other HTTP headers. It allows Java test code to examine returned pages either as text, an XML DOM, or as collections of forms, tables, and links.

References

  1. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 92. ISBN   978-0-596-10180-0. Javascript lacks a portable mechanism for general network communication[.] ... But thanks to the XMLHttpRequest object, ... Javascript code can make HTTP calls back to its originating server[.]
  2. 1 2 Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 92. ISBN   978-0-596-10180-0.
  3. "Article on the history of XMLHTTP by an original developer". Alexhopmann.com. 2007-01-31. Archived from the original on 2009-01-30. Retrieved 2009-07-14. The reality is that the client architecture of GMail appears to follow the rough design of the Exchange 2000 implementation of Outlook Web Access for IE5 and later which shipped way back in 2000.
  4. 1 2 Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 93. ISBN   978-0-596-10180-0.
  5. "Archived news from Mozillazine stating the release date of Safari 1.2". Weblogs.mozillazine.org. Archived from the original on 2009-06-02. Retrieved 2009-07-14.
  6. "Press release stating the release date of Opera 8.0 from the Opera website". Opera.com. 2005-04-19. Retrieved 2009-07-14.
  7. "Specification of the XMLHttpRequest object from the Level 1 W3C Working Draft released on April 5th, 2006". W3.org. Retrieved 2009-07-14.
  8. "Specification of the XMLHttpRequest object from the Level 2 W3C Working Draft released on February 25th, 2008". W3.org. Retrieved 2009-07-14.
  9. "XMLHttpRequest Editor's Draft 5 December 2011". w3.org. Retrieved 5 December 2011.
  10. van Kesteren, Anne (February 19, 2024). XMLHttpRequest Living Standard (Report). Retrieved 2024-04-09.
  11. Holdener, Anthony T. III (2008). Ajax: The Definitive Guide. pp. 70–71, 76.
  12. van Kesteren, 3.5.2.
  13. van Kesteren, 3.5.6.
  14. van Kesteren, 3.6.9.
  15. van Kesteren, 3.5.7.
  16. van Kesteren, 3.5.3.
  17. "XMLHttpRequest Level 2" . Retrieved 2013-11-14.
  18. "Can I use Cross-Origin Resource Sharing?" . Retrieved 2013-11-14.
  19. "XDomainRequest - Restrictions, Limitations and Workarounds" . Retrieved 2013-11-14.
  20. "7.1.5 Cross-Origin Request with Preflight" . Retrieved 2014-04-25.
  21. "Fetch Standard".

Notes

  1. The standard was edited by Anne van Kesteren of Opera Software and Dean Jackson of W3C.