XMLHttpRequest
Encyclopedia
XMLHttpRequest is an API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 available in web browser
Web browser
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...

 scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

s such as JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

. It is used to send HTTP
Hypertext Transfer Protocol
The Hypertext Transfer Protocol is a networking protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web....

 or HTTPS requests directly to a web server
Web server
Web server can refer to either the hardware or the software that helps to deliver content that can be accessed through the Internet....

 and load the server response data directly back into the script. The data might be received from the server as XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....

 text or as plain text
Plain text
In computing, plain text is the contents of an ordinary sequential file readable as textual material without much processing, usually opposed to formatted text....

. Data from the response can be used directly to alter the DOM
Document Object Model
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...

 of the currently active document in the browser window without loading a new web page
Web page
A web page or webpage is a document or information resource that is suitable for the World Wide Web and can be accessed through a web browser and displayed on a monitor or mobile device. This information is usually in HTML or XHTML format, and may provide navigation to other web pages via hypertext...

 document. The response data can also be evaluated
Interpreter (computing)
In computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language...

 by client-side scripting. For example, if it was formatted as JSON
JSON
JSON , or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects...

 by the web server, it can easily be converted into a client-side data object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 for further use.

XMLHttpRequest has an important role in the Ajax
Ajax (programming)
Ajax is a group of interrelated web development methods used on the client-side to create asynchronous web applications...

 web development technique. It is currently used by many websites to implement responsive and dynamic web application
Web application
A web application is an application that is accessed over a network such as the Internet or an intranet. The term may also mean a computer software application that is coded in a browser-supported language and reliant on a common web browser to render the application executable.Web applications are...

s. Examples of these web applications include Gmail
Gmail
Gmail is a free, advertising-supported email service provided by Google. Users may access Gmail as secure webmail, as well via POP3 or IMAP protocols. Gmail was launched as an invitation-only beta release on April 1, 2004 and it became available to the general public on February 7, 2007, though...

, Google Maps
Google Maps
Google Maps is a web mapping service application and technology provided by Google, free , that powers many map-based services, including the Google Maps website, Google Ride Finder, Google Transit, and maps embedded on third-party websites via the Google Maps API...

, Facebook
Facebook
Facebook is a social networking service and website launched in February 2004, operated and privately owned by Facebook, Inc. , Facebook has more than 800 million active users. Users must register before using the site, after which they may create a personal profile, add other users as...

 and many others.

XMLHttpRequest is subject to the browser's same origin policy
Same origin policy
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...

 in that, for security reasons, requests will only succeed if they are made to the same server that served the original web page. There are alternative ways to circumvent this policy if required.

History and support

The concept behind the XMLHttpRequest object was originally created by the developers of Outlook Web Access
Outlook Web Access
Outlook Web App , originally called Outlook Web Access and before that Exchange Web Connect , is a webmail service of Microsoft Exchange Server 5.0 and later...

 (by Microsoft) for Microsoft Exchange Server 2000. An interface
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 called IXMLHTTPRequest was developed and implemented into the second version of the MSXML
MSXML
Microsoft XML Core Services is a set of services that allow applications written in JScript, VBScript, and Microsoft development tools to build Windows-native XML-based applications...

 library using this concept. The second version of the MSXML library was shipped with Internet Explorer 5.0 in March 1999, allowing access, via ActiveX
ActiveX
ActiveX is a framework for defining reusable software components in a programming language-independent way. Software applications can then be composed from one or more of these components in order to provide their functionality....

, to the IXMLHTTPRequest interface using the XMLHTTP wrapper
Adapter pattern
In computer programming, the adapter pattern is a design pattern that translates one interface for a class into a compatible interface...

 of the MSXML library.

The Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....

 project developed and implemented an interface called nsIXMLHttpRequest into the Gecko
Gecko (layout engine)
Gecko is a free and open source layout engine used in many applications developed by Mozilla Foundation and the Mozilla Corporation , as well as in many other open source software projects....

 layout engine. This interface was modelled 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 of 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
De facto standard
A de facto standard is a custom, convention, product, or system that has achieved a dominant position by public acceptance or market forces...

 amongst other major web clients, implemented in Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...

 1.2 released in February 2004, Konqueror
Konqueror
Not to be confused with the Conqueror web browser.Konqueror is a web browser and file manager that provides file-viewer functionality for file systems such as local files, files on a remote ftp server and files in a disk image. It is a core part of the KDE desktop environment...

, Opera
Opera (web browser)
Opera is a web browser and Internet suite developed by Opera Software with over 200 million users worldwide. The browser handles common Internet-related tasks such as displaying web sites, sending and receiving e-mail messages, managing contacts, chatting on IRC, downloading files via BitTorrent,...

 8.0 released in April 2005, and iCab
ICab
iCab is a web browser for the Macintosh by Alexander Clauss, derived from Crystal Atari Browser for Atari TOS compatible computers. It is the most recently actively developed browser for 68k-based Macintoshes that features tabbed browsing and one of a very few browsers that was still updated in...

 3.0b352 released in September 2005.

The World Wide Web Consortium
World Wide Web Consortium
The World Wide Web Consortium is the main international standards organization for the World Wide Web .Founded and headed by Tim Berners-Lee, the consortium is made up of member organizations which maintain full-time staff for the purpose of working together in the development of standards for the...

 published a Working Draft specification for the XMLHttpRequest object on April 5, 2006, edited
Copy editing
Copy editing is the work that an editor does to improve the formatting, style, and accuracy of text. Unlike general editing, copy editing might not involve changing the substance of the text. Copy refers to written or typewritten text for typesetting, printing, or publication...

 by Anne van Kesteren of Opera Software
Opera Software
Opera Software ASA is a Norwegian software company, primarily known for its Opera family of web browsers with over 220 million users worldwide. Opera Software is also involved in promoting Web standards through participation in the W3C. The company has its headquarters in Oslo, Norway and is...

 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 last revision to the XMLHttpRequest object specification was on November 19 of 2009, being a last call working draft.
Microsoft added the XMLHttpRequest object identifier to its scripting languages in Internet Explorer 7.0 released in October 2006.

With the advent of cross-browser JavaScript libraries such as jQuery
JQuery
jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 at BarCamp NYC by John Resig...

 and the Prototype JavaScript Framework
Prototype Javascript Framework
The Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson in February 2005 as part of the foundation for Ajax support in Ruby on Rails. It is implemented as a single file of JavaScript code, usually named prototype.js...

, developers can invoke XMLHttpRequest functionality without coding directly to the API. Prototype provides an asynchronous requester object called Ajax.Request that wraps the browser's underlying implementation and provides access to it. jQuery objects represent or wrap elements
HTML element
An HTML element is an individual component of an HTML document. HTML documents are composed of a tree of HTML elements and other nodes, such as text nodes. Each element can have attributes specified. Elements can also have content, including other elements and text. HTML elements represent...

 from the current client-side DOM. They all have a .load method that takes a URI parameter and makes an XMLHttpRequest to that URI, then by default places any returned HTML into the HTML element represented by the jQuery object.

The W3C has since published another Working Draft specification for the XMLHttpRequest object, "XMLHttpRequest Level 2", on February 25 of 2008. Level 2 consists of extended functionality to the XMLHttpRequest object, including, but not currently limited to, progress events, support for cross-site requests, and the handling of byte streams. The latest revision of the XMLHttpRequest Level 2 specification is that of 16 August 2011, which is still a working draft.

Support in Internet Explorer versions 5, 5.5 and 6

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
In the context of telecommunications and computing, a device or technology is said to be backward or downward compatible if it can work with input generated by an older device...

 can be achieved through object detection if the XMLHttpRequest identifier does not exist.

Web pages that use XMLHttpRequest or XMLHTTP can mitigate the current minor differences in the implementations either by encapsulating the XMLHttpRequest object in a JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 wrapper, or by using an existing framework that does so. In either case, the wrapper should detect the abilities of current implementation and work within its requirements.

Since Microsoft still supports Windows XP with Internet Explorer 6, a JavaScript encapsulation example is provided below.


/*
Provide the XMLHttpRequest constructor for Internet Explorer 5.x-6.x:
Other browsers (including Internet Explorer 7.x-9.x) do not redefine
XMLHttpRequest if it already exists.

This example is based on findings at:
http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if (typeof XMLHttpRequest "undefined")
XMLHttpRequest = function {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
//Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
throw new Error("This browser does not support XMLHttpRequest.");
};

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
Hypertext Transfer Protocol
The Hypertext Transfer Protocol is a networking protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web....

 and HTTPS requests of the XMLHttpRequest object must be initialized through the open method
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

. This method must be invoke
Execution (computers)
Execution in computer and software engineering is the process by which a computer or a virtual machine carries out the instructions of a computer program. The instructions in the program trigger sequences of simple actions on the executing machine...

d prior to the actual sending of a request to validate and resolve the request method, URL
Uniform Resource Locator
In computing, a uniform resource locator or universal resource locator is a specific character string that constitutes a reference to an Internet resource....

, and URI
Uniform Resource Identifier
In computing, a uniform resource identifier is a string of characters used to identify a name or a resource on the Internet. Such identification enables interaction with representations of the resource over a network using specific protocols...

 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
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...

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
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....

 indicating the HTTP request method to use. The request methods that must be supported by a conforming user agent
User agent
In computing, a user agent is a client application implementing a network protocol used in communications within a client–server distributed computing system...

, defined by the W3C draft for the XMLHttpRequest object, are currently listed as the following.
  • GET (Supported by Internet Explorer 7 (and later), Mozilla 1+
    Mozilla Application Suite
    The Mozilla Application Suite is a cross-platform integrated Internet suite. Its development was initiated by Netscape Communications Corporation, before their acquisition by AOL. It is based on the source code of Netscape Communicator...

    )
  • POST
    POST (HTTP)
    In computing, POST is one of many request methods supported by the HTTP protocol used by the World Wide Web. The POST request method is used when the client needs to send data to the server as part of the request, such as when uploading a file or submitting a completed form.In contrast to the GET...

     (Supported by Internet Explorer 7 (and later), Mozilla 1 (and later))
  • HEAD (Supported by Internet Explorer 7 (and later))
  • PUT
  • DELETE
  • OPTIONS (Supported by Internet Explorer 7 (and later))

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
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....

, 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
TCP and UDP port
In computer networking, a port is an application-specific or process-specific software construct serving as a communications endpoint in a computer's host operating system. A port is associated with an IP address of the host, as well as the type of protocol used for communication...

 or ihost URI
Úri
Úriis a village and commune in the comitatus of Pest in Hungary....

 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 on with the execution of the current script. It will instead invoke
Execution (computers)
Execution in computer and software engineering is the process by which a computer or a virtual machine carries out the instructions of a computer program. The instructions in the program trigger sequences of simple actions on the executing machine...

 the onreadystatechange event listener 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.

The fourth and fifth parameters are the user
User (computing)
A user is an agent, either a human agent or software agent, who uses a computer or network service. A user often has a user account and is identified by a username , screen name , nickname , or handle, which is derived from the identical Citizen's Band radio term.Users are...

name and password
Password
A password is a secret word or string of characters that is used for authentication, to prove identity or gain access to a resource . The password should be kept secret from those not allowed access....

, respectively. These parameters, or just the username, may be provided for authentication and authorization if required by the server for this request.

The setRequestHeader method

Upon successful initialization of a request, the setRequestHeader method of the XMLHttpRequest object can be invoked to send HTTP headers 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.

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
Proxy server
In computer networks, a proxy server is a server that acts as an intermediary for requests from clients seeking resources from other servers. A client connects to the proxy server, requesting some service, such as a file, connection, web page, or other resource available from a different server...

, 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:
  • After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1.
  • 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.
  • Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3.
  • Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4.


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.


xmlhttp.onreadystatechange = function {
alert(xmlhttp.readyState);
};
xmlhttp.open("GET","somepage.xml",true);
xmlhttp.send(null);

The HTTP response

After a successful and completed call to the send method of the XMLHttpRequest, if the server response was valid XML and the Content-Type header sent by the server is understood by the user agent as an Internet media type
Internet media type
An Internet media type, originally called a MIME type after MIME and sometimes a Content-type after the name of a header in several protocols whose value is such a type, is a two-part identifier for file formats on the Internet.The identifiers were originally defined in RFC 2046 for use in email...

 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
World Wide Web
The World Wide Web is a system of interlinked hypertext documents accessed via the Internet...

, 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 origin policy
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...

 that prevents many such attacks, such as cross-site scripting
Cross-site scripting
Cross-site scripting is a type of computer security vulnerability typically found in Web applications that enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same...

. XMLHttpRequest data is subject to this security policy, but sometimes web developers want intentionally to 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 or alternatives with plugins such as Flash or Silverlight. XMLHttpRequest Level 2 also includes a feature to communicate with other domains. This is implemented in Firefox 3.5, Google Chrome, and Safari 4. Internet Explorer 8 has the non-standard XDomainRequest, which can do a similar thing.

Headers added to a server's HTTP response headers can allow cross-domain requests to succeed. For example, Access-Control-Allow-Origin: *, can allow all domains to access a server. Access-Control-Allow-Origin can be used in all browsers that support cross-domain requests, which includes Internet Explorer 8. The W3C's specification is defined in Cross-Origin Resource Sharing
Cross-Origin Resource Sharing
Cross-Origin Resource Sharing is a web browser technology specification, which defines ways for a web server to allow its resources be accessed by a web page from a different domain...

.
See also
  • WebSockets
    WebSockets
    WebSocket is a technology providing for bi-directional, full-duplex communications channels, over a single Transmission Control Protocol socket. It is designed to be implemented in web browsers and web servers, but it can be used by any client or server application...

  • Hypertext Transfer Protocol
    Hypertext Transfer Protocol
    The Hypertext Transfer Protocol is a networking protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web....

  • Representational State Transfer
    Representational State Transfer
    Representational state transfer is a style of software architecture for distributed hypermedia systems such as the World Wide Web. The term representational state transfer was introduced and defined in 2000 by Roy Fielding in his doctoral dissertation...

  • Ajax
    Ajax (programming)
    Ajax is a group of interrelated web development methods used on the client-side to create asynchronous web applications...


Specifications


Browsers


Other

  • "Attacking AJAX Applications", a presentation given at the Black Hat
    Black Hat Briefings
    The Black Hat Conference is a computer security conference that brings together a variety of people interested in information security. Representatives of federal agencies and corporations attend along with hackers. The Briefings take place regularly in Las Vegas, Barcelona and Tokyo...

    security conference. Discusses several issues involving XHR and the future of cross-domain Ajax.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK