← Back to results

XMLHttpRequest - Wikipedia Jump to content Main menu

Main menu move to sidebar hide Navigation Main page Contents Current events Random article About Wikipedia Contact us Contribute Help Learn to edit Community portal Recent changes Upload file Special pages Search Search Appearance Donate Create account Log in Personal tools Donate Create account Log in Contents move to sidebar hide (Top) 1 History Toggle History subsection 1.1 Standards 2 Usage 3 Cross-domain requests 4 Fetch alternative Toggle Fetch alternative subsection 4.1 Example 5 See also 6 References 7 Notes 8 External links Toggle the table of contents XMLHttpRequest 26 languages العربية Català Čeština Deutsch Español Eesti فارسی Français Magyar Bahasa Indonesia Íslenska Italiano 日本語 한국어 Nederlands Polski Português Română Русский Српски / srpski Svenska ไทย Türkmençe Türkçe Українська 中文 Edit links Article Talk English Read Edit View history Tools Tools move to sidebar hide Actions Read Edit View history General What links here Related changes Upload file Permanent link Page information Cite this page Get shortened URL Switch to legacy parser Print/export Download as PDF Printable version In other projects Wikibooks Wikidata item Appearance move to sidebar hide From Wikipedia, the free encyclopedia Web API to transfer data between a web browser and a web server HTTP Persistence Compression HTTPS QUIC Request methods OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT PATCH Header fields Cookie ETag Location HTTP referer DNT X-Forwarded-For Upgrade Response status codes 301 Moved Permanently 302 Found 303 See Other 403 Forbidden 404 Not Found 451 Unavailable for Legal Reasons Security access control methods Basic access authentication Digest access authentication Security vulnerabilities HTTP header injection HTTP request smuggling HTTP response splitting HTTP parameter pollution v t e 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 send requests to the server after page loading is complete, and receive information back.[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] History [edit] 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 (1999). 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 [edit] The World Wide Web Consortium (W3C) published a Working Draft specification for the XMLHttpRequest object on April 5, 2006.[7][a] 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 [edit] Example in TypeScript.[11] {\n // The request is done. Log response status code and text\n console.log(xhr.status, xhr.responseText);\n};\n\nxhr.onerror = () => {\n console.log('Network error occurred');\n};\n\n// Send request\nxhr.send();\n"}}'> // Create XMLHttpRequest object const xhr = new XMLHttpRequest(); // Configure request: GET method, URL, Async flag (true) makes script not stop while waiting for response xhr.open('GET', 'https://example.com', true); // Set event listeners xhr.onload = () => { // The request is done. Log response status code and text console.log(xhr.status, xhr.responseText); }; xhr.onerror = () => { console.log('Network error occurred'); }; // Send request xhr.send(); 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 [edit] Main article: Cross-origin resource sharing 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 [edit] 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 [edit] {\n if (response.status !== 200) {\n throw new Error('Request failed');\n }\n return response.text();\n })\n .then((text: string) => {\n console.log(text);\n })\n .catch((error: Error) => {\n console.error(error.message);\n });\n"}}'> fetch('/api/message') .then((response: Response) => { if (response.status !== 200) { throw new Error('Request failed'); } return response.text(); }) .then((text: string) => { console.log(text); }) .catch((error: Error) => { console.error(error.message); }); See also [edit] WebSocket Representational state transfer (REST) References [edit] ↑ Mahemoff, Michael (2007). 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[.] 1 2 Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 92. ISBN 978-0-596-10180-0. ↑ "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. 1 2 Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 93. ISBN 978-0-596-10180-0. ↑ "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. ↑ "Press release stating the release date of Opera 8.0 from the Opera website". Opera.com. 2005-04-19. Retrieved 2009-07-14. ↑ "Specification of the XMLHttpRequest object from the Level 1 W3C Working Draft released on April 5th, 2006". W3.org. Retrieved 2009-07-14. ↑ "Specification of the XMLHttpRequest object from the Level 2 W3C Working Draft released on February 25th, 2008". W3.org. Retrieved 2009-07-14. ↑ "XMLHttpRequest Editor's Draft 5 December 2011". w3.org. Retrieved 5 December 2011. ↑ van Kesteren, Anne (February 19, 2024). XMLHttpRequest Living Standard (Report). Retrieved 2024-04-09. ↑ Holdener, Anthony T. III (2008). Ajax: The Definitive Guide. pp. 70–71, 76. ↑ van Kesteren 2024, 3.5.2. ↑ van Kesteren 2024, 3.5.6. ↑ van Kesteren 2024, 3.6.9. ↑ van Kesteren 2024, 3.5.7. ↑ van Kesteren 2024, 3.5.3. ↑ "XMLHttpRequest Level 2". Retrieved 2013-11-14. ↑ "Can I use Cross-Origin Resource Sharing?". Retrieved 2013-11-14. ↑ "XDomainRequest - Restrictions, Limitations and Workarounds". Retrieved 2013-11-14. ↑ "7.1.5 Cross-Origin Request with Preflight". Retrieved 2014-04-25. ↑ "Fetch Standard". Notes [edit] ↑ The standard was edited by Anne van Kesteren of Opera Software and Dean Jackson of W3C. External links [edit] Wikibooks has a book on the topic of: XMLHttpRequest XMLHttpRequest Living Standard by the WHATWG XMLHttpRequest Level 1 draft by the W3C v t e Internet Explorer Versions Main 1 2 3 4 5 6 7 8 9 10 11 Other Mobile for Mac for UNIX IEs4Linux Overview History Add-ons Box model Browser Helper Object (BHO) Extensions Removal Shells Technologies Accelerator ActiveX HTML HTA HTML Components favicon.ico HTML+TIME Index.dat JScript MHTML MSXML Smart tags Temporary Internet Files Vector Markup Language Web Slice WPAD XHR/XDomainRequest Software and engines Administration Kit Developer Tools Integrated Windows Authentication Tasman MSHTML Chakra Implementations Active Channel Active Desktop ActiveMovie Channel Definition Format (.cdf) Comic Chat/Chat 2.0 DirectX Media Internet Mail and News Microsoft Java Virtual Machine (MSJVM) MSN Explorer MSN for Mac OS X MSN Program Viewer NetMeeting NetShow Outlook Express Server Gated Cryptography (SGC) Spyglass Windows Address Book Windows Desktop Update Events First Browser War Second Browser War Download.ject Eolas v. Microsoft Sun v. Microsoft United States v. Microsoft Corp. People Tantek Çelik Thomas Reardon Dean Hachamovitch Scott Isaacs Inori Aizawa Category v t e World Wide Web Consortium (W3C) Products, standards Recommendations ActivityPub Activity Streams ARIA Canonical XML CDF CSS Animations Flexbox Grid DOM EXI EmotionML Geolocation API GRDDL HTML HTML5 IndexedDB ITS JSON-LD Linked Data Notifications MathML Micropub MTOM OWL PLS RDF Schema RDFa RIF SAWSDL SISR SKOS SMIL SOAP SRGS SRI SSML SVG Animation Filter Effects SCXML SHACL SPARQL Timed text VoiceXML WebAssembly WoT TD Web storage WSDL Webmention WebSub WebVTT WOFF WS-Addressing XHTML +RDFa XML Base Encryption Events Information Set Namespace Schema Signature XForms XInclude XLink XOP XPath 2.0 3.x XPointer XProc XQuery XSL XSL-FO XSLT elements Notes IndieAuth XAdES XBL XHTML+SMIL XUP Working drafts CCXML CURIE EME InkML MSE SMIL Timesheets sXBL WebGPU WebXR XFDL XFrames XMLHttpRequest Guidelines Web Content Accessibility Guidelines Initiative Markup Validation Service Web Accessibility Initiative Web Components Deprecated C-HTML HDML JSSS PGML VML WebPlatform Obsoleted P3P XHTML+MathML+SVG Groups, organizations WHATWG Defunct: World Wide Web Foundation Elected AB Board TAG Working CSS SVG WebAssembly WebAuthn Community, business Web Advertising BG WebAssembly CG Closed Device Description (DDWG) HTML Multimodal Interaction Activity (MMI) Software CERN httpd Libwww Browsers Line Mode (1990–) Arena (1993–98) Agora (1994–97) Argo (1994–97) Amaya (browser/editor, 1996–2012) Conferences International World Wide Web Conference (IW3C) Steering Committee (IW3C2) First conference ("WWW1", 1994) v t e Web interfaces Server-side Protocols HTTP v2 v3 Encryption WebDAV CGI SCGI FCGI AJP WSRP WebSocket Server APIs C NSAPI C ASAPI C ISAPI COM ASP Jakarta Servlet container CLI OWIN ASP.NET Handler Python WSGI Python ASGI Ruby Rack JavaScript JSGI Perl PSGI Portlet container Apache modules mod_include mod_jk mod_lisp mod_mono mod_parrot mod_perl mod_php mod_proxy mod_python mod_wsgi mod_ruby Phusion Passenger Topics Web service vs. Web resource WOA vs. ROA Open API Webhook Application server comparison Scripting Client-side Browser APIs C NPAPI LiveConnect XPConnect C NPRuntime C PPAPI NaCl ActiveX BHO XBAP Web APIs WHATWG Audio Canvas DOM SSE Video WebSockets Web messaging Web storage Web worker XMLHttpRequest W3C DOM events EME File Geolocation IndexedDB MSE SVG WebAssembly WebAuthn WebGPU WebRTC WebXR Khronos WebCL WebGL Others Gears Web SQL Database (formerly W3C) WebUSB Topics Ajax and Remote scripting vs. DHTML Browser extension Cross-site scripting and CORS Hydration Mashup Persistent data Web IDL Scripting Related topics Frontend and backend Microservices REST GraphQL Push technology Solution stack Web page Static Dynamic Web standards Web API security Web application Rich Single-page Progressive Web framework Retrieved from "https://en.wikipedia.org/w/index.php?title=XMLHttpRequest&oldid=1339793906" Categories: XML Microsoft application programming interfaces Microsoft initiatives JavaScript Hypertext Transfer Protocol clients Ajax (programming) Web standards 2000 software Hidden categories: Articles with short description Short description is different from Wikidata Articles with example JavaScript code This page was last edited on 22 February 2026, at 10:18 (UTC). Page was rendered with Parsoid. Text is available under the Creative Commons Attribution-ShareAlike 4.0 License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Privacy policy About Wikipedia Disclaimers Contact Wikipedia Legal & safety contacts Code of Conduct Developers Statistics Cookie statement Mobile view Search Search Toggle the table of contents XMLHttpRequest 26 languages Add topic