XMLHttpRequest

XMLHttpRequest (XHR) is a JavaScript class containing methods to asynchronously transmit HTTP requests from a web browser to a web server. The methods allow a browser-based application to make a fine-grained server call and store the results in XMLHttpRequest's responseText attribute. The XMLHttpRequest class is a component of Ajax programming. Prior to Ajax, an HTML form needed to be completely sent to the server followed by a complete browser page refresh.
History
The concept behind the XMLHttpRequest class was conceived in 2000 by the developers of Microsoft Outlook – available on the Windows 2000 operating system. The concept was then implemented within the Internet Explorer 5 (2001) browser's interpreter. However, the original syntax did not use the XMLHttpRequest identifier. Instead, the developers used the identifiers ActiveXObject("Msxml2.XMLHTTP") and ActiveXObject("Microsoft.XMLHTTP"). As of Internet Explorer 7 (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), Konqueror (2002), Safari 1.2 (2004), Opera 8.0 (2005) and iCab (2005).
With the advent of cross-browser JavaScript libraries such as jQuery, developers can invoke XMLHttpRequest functionality indirectly.
Standards
The World Wide Web Consortium (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 took over development and maintains a living document using Web IDL.
XMLHttpRequest usage
Constructor
Generating an asynchronous request to the web server requires first to instantiate (allocate the memory of) the XMLHttpRequest object. The allocated memory is assigned to a variable. The programming statement in JavaScript to instantiate a new object is new. The new statement is followed by the constructor function of the object. The custom for object-oriented language developers is to invoke the constructor function using same name as the class name. In this case, the class name is XMLHttpRequest. To instantiate a new XMLHttpRequest and assign it to the variable named request:
var request = new XMLHttpRequest();
The open method
The open method prepares the XMLHttpRequest. It can accept up to five parameters, but requires only the first two.
var request = new XMLHttpRequest();
request.open(RequestMethod, SubmitURL, AsynchronousBoolean, UserName, Password );
RequestMethod: The HTTP request method may be GET for typical quantities of data. Among the other request methods available, POST will handle substantial quantities of data. After the return string is received, then send the DELETE request method to .open() to free the XMLHttpRequest memory. If DELETE is sent, then the SubmitURL parameter may be null.
* request.open("DELETE", null );
SubmitURL: The SubmitURL is a URL containing the execution filename and any parameters that get submitted to the web server. If the URL contains the host name, it must be the web server that sent the HTML document. Ajax supports the same-origin policy.
AsynchronousBoolean: If supplied, it should be set to true. If set to false, then the browser will wait until the return string is received. Programmers are discouraged to set AsynchronousBoolean to false, and browsers may experience an exception error.
UserName: If supplied, it will help authenticate the user.
Password: If supplied, it will help authenticate the user.
The setRequestHeader method
If the request method of POST is invoked, then the additional step of sending the media type of Content-Type: application/x-www-form-urlencoded is required. The setRequestHeader method allows the program to send this or other HTTP headers to the web server. Its usage is setRequestHeader(HeaderField, HeaderValue ). To enable the POST request method:
* request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded" );
The send method
If the request method of POST is invoked, then the web server expects the form data to be read from the standard input stream. To send the form data to the web server, execute request.send(FormData ), where FormData is a text string. If the request method of GET is invoked, then the web server expects only the default headers. To send the default headers, execute request.send(null ).
The onreadystatechange event listener
onreadystatechange is a callback method that is periodically executed throughout the Ajax lifecycle. To set a callback method named ReadyStateMethod(), the syntax is request.onreadystatechange = ReadyStateMethod. For convenience, the syntax allows for an anonymous method to be defined. To define an anonymous callback method:
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
// code omitted
}
The XMLHttpRequest lifecycle progresses through several stages – from 0 to 4. Stage 0 is before the open() method is invoked, and stage 4 is when the text string has arrived. To monitor the lifecycle, XMLHttpRequest has available the readyState attribute. Stages 1-3 are ambiguous and interpretations vary across browsers. Nonetheless, one interpretation is:
Stage 0: Uninitialized
Stage 1: Loading
Stage 2: Loaded
Stage 3: Interactive
Stage 4: Completed
When readyState reaches 4, then the text string has arrived and is set in the responseText attribute.
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4 )
{
// request.responseText is set
}
}
Linux examples
Upon request, the browser will execute a JavaScript function to transmit a request for the web server to execute a computer program. The computer program may be the PHP interpreter, another interpreter, or a compiled executable. In any case, the JavaScript function expects a text string to be transmitted back and stored in the responseText attribute.
To create an example JavaScript function:
cd /var/www/html
Edit a file named ajax_submit.js:
function ajax_submit(element_id, submit_url )
{
var request = new XMLHttpRequest();
var completed_state = 4;
request.onreadystatechange = function()
{
if (request.readyState == completed_state )
{
document.
getElementById(element_id ).
innerHTML =
request.responseText;
request.open("DELETE", null );
}
}
request.open("GET", submit_url );
request.send(null );
}
PHP example
PHP is a scripting language designed specifically to interface with HTML. Because the PHP engine is an interpreter – interpreting program statements as they are read – there are programming limitations and performance costs. Nonetheless, its simplicity may place the XMLHttpRequest set of files in the same working directory – probably /var/www/html.
PHP server component
The server component of a PHP XMLHttpRequest is a file located on the server that doesn't get transmitted to the browser. Instead, the PHP interpreter will open this file and read in its PHP instructions. The XMLHttpRequest protocol requires it to output a text string.
cd /var/www/html
Edit a file named ajax.phtml:
<?php
echo '<h1>Hello World!</h1>';
?>
PHP browser component
The browser component of a PHP XMLHttpRequest is a file located on the server that gets transmitted to the browser. The browser will open this file and read in its HTML instructions.
cd /var/www/html
Edit a file named ajax.html:
<html>
<head>
<title>Hello World</title>
<script type=text/javascript src=ajax_submit.js></script>
</head>
<body>
<div id=ajax_title></div>
<button onclick="ajax_submit('ajax_title', 'ajax.phtml' )">
Submit
</button>
</body>
Point your browser to http://localhost/ajax.html
Press Submit
CGI example
The Common Gateway Interface (CGI) process allows browsers to request the web server to execute compiled computer programs.
CGI server component
The server component of a CGI XMLHttpRequest is an executable file located on the server. The operating system will open this file and read in its machine instructions. The XMLHttpRequest protocol requires the executable to output a text string.
Compiled programs have two files: the source code and a corresponding executable.
cd /usr/lib/cgi-bin
Edit a file named ajax.c:
#include <stdio.h>
void main(void )
{
/* CGI requires the first line to output: */
printf("Content-type: text/html\n" );
/* CGI requires the second line to output: */
printf("\n" );
printf("<h1>Hello World!</h1>\n" );
}
Compile the source code to create the executable:
cc ajax.c -o ajax
or
sudo cc ajax.c -o ajax
CGI browser component
The CGI browser component is the same as the PHP browser component, except for a slight change in the submit_url. The syntax to tell the web server to execute an executable is /cgi-bin/ followed by the filename. For security, the executable must reside in a chroot jail. In this case, the jail is the directory /usr/lib/cgi-bin/.
cd /var/www/html
Edit a file named ajax.html:
<html>
<head>
<title>Hello World</title>
<script type=text/javascript src=ajax_submit.js></script>
</head>
<body>
<div id=ajax_title></div>
<button onclick="ajax_submit('ajax_title', '/cgi-bin/ajax' )">
Submit
</button>
</body>
Point your browser to http://localhost/ajax.html
Press Submit
See also
WebSocket
Representational state transfer (REST)
References
Notes
External links
XMLHttpRequest Living Standard by the WHATWG
XMLHttpRequest Level 1 draft by the W3C
XML
Microsoft application programming interfaces
Microsoft initiatives
JavaScript
Hypertext Transfer Protocol clients
Ajax (programming)
Articles with example JavaScript code
Web standards
2000 software