XMLHttpRequest

XMLHttpRequest (XHR) is a JavaScript class[lower-alpha 1] containing methods to asynchronously 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] 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.[2]

History

The concept behind the XMLHttpRequest class was conceived in 2000 by the developers of Microsoft Outlook – available on the Windows 2000 operating system.[3] The concept was then implemented within the Internet Explorer 5 (2001) browser's interpreter.[lower-alpha 2] 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), Konqueror (2002), Safari 1.2 (2004),[5] Opera 8.0 (2005),[6], and iCab (2005).[7]

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.[8] [lower-alpha 3] On February 25, 2008, the W3C published the Working Draft Level 2 specification.[9] 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.[10]

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

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.[12] 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.[13] 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();[14]

The open method

The open method prepares the XMLHttpRequest.[15] 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.[16] After the return string is received, then send the DELETE request method to .open() to free the XMLHttpRequest memory.[17] 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.[18]
  • 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.[19]
  • 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.[20] The setRequestHeader method allows the program to send this or other HTTP headers to the web server. Its usage is setRequestHeader( HeaderField, HeaderValue ).[15] 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.[21] 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.[22] To send the default headers, execute request.send( null ).[lower-alpha 4]

The onreadystatechange event listener

onreadystatechange is a callback method that is periodically executed throughout the Ajax lifecycle.[23] To set a callback method named ReadyStateMethod(), the syntax is request.onreadystatechange = ReadyStateMethod.[lower-alpha 5] For convenience, the syntax allows for an anonymous method to be defined.[23] 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.[22] To monitor the lifecycle, XMLHttpRequest has available the readyState attribute. Stages 1-3 are ambiguous and interpretations vary across browsers.[15] Nonetheless, one interpretation is:[15]

  • 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.[22]

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.[24] Because the PHP engine is an interpreter – interpreting program statements as they are read – there are programming limitations[lower-alpha 6] and performance costs.[lower-alpha 7] 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>

CGI example

The Common Gateway Interface (CGI) process allows browsers to request the web server to execute compiled computer programs.[lower-alpha 8]

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/.[lower-alpha 9]

  • 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>

See also

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. 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. 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. Soft-Info.org. "Detailed browser information stating the release date of iCab 3.0b352". Soft-Info.com. Retrieved 2009-07-14.
  8. "Specification of the XMLHttpRequest object from the Level 1 W3C Working Draft released on April 5th, 2006". W3.org. Retrieved 2009-07-14.
  9. "Specification of the XMLHttpRequest object from the Level 2 W3C Working Draft released on February 25th, 2008". W3.org. Retrieved 2009-07-14.
  10. "XMLHttpRequest Editor's Draft 5 December 2011". w3.org. Retrieved 5 December 2011.
  11. "XMLHttpRequest Standard/#specification-history".
  12. Flanagan, David (1998). JavaScript, The Definitive Guide. O'Reilly and Associates. p. 82. ISBN 1-56592-392-8.
  13. Welling, Luke; Thomson, Laura (2005). PHP and MySQL Web Development. Sams Publishing. p. 162. ISBN 0-672-32672-8.
  14. "XMLHttpRequest Standard; The constructor". Retrieved 2023-04-10.
  15. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 100. ISBN 978-0-596-10180-0.
  16. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 96. ISBN 978-0-596-10180-0.
  17. "HTTP Documentation". June 2022. Retrieved 2023-04-12.
  18. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 98. ISBN 978-0-596-10180-0.
  19. "XMLHttpRequest Standard; The open method". Retrieved 2023-04-12.
  20. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 97. ISBN 978-0-596-10180-0.
  21. Flanagan, David (1998). JavaScript, The Definitive Guide. O'Reilly and Associates. p. 511. ISBN 1-56592-392-8.
  22. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 26. ISBN 978-0-596-10180-0.
  23. Mahemoff, Michael (2006). Ajax Design Patterns. O'Reilly. p. 25. ISBN 978-0-596-10180-0.
  24. Welling, Luke; Thomson, Laura (2005). PHP and MySQL Web Development. Sams Publishing. p. 2. ISBN 0-672-32672-8. PHP is a server-side scripting language designed specifically for the Web.
  25. "Apache Tutorial". Retrieved 2023-04-10.

Notes

  1. Although sources may call XMLHttpRequest an API, it is technically a class that is instantiated to an object variable using the new statement.
  2. Modern browsers execute JavaScript using a just-in-time compiler called a JavaScript engine.
  3. The standard was edited by Anne van Kesteren of Opera Software and Dean Jackson of W3C.
  4. The null placeholder is currently in retirement but recommended.
  5. For safety, this assignment should follow the execution of request.open().
  6. Whereas PHP is a rich language and interfaces well with certain databases, it supports only a subset of container types and lacks declarative language constructs.
  7. An interpreter executes each programming statement; however, a compiled program has each machine instruction ready for the CPU.
  8. The web server may be configured to execute interpreted programs, also.[25]
  9. The web server may be configured to add other executable directories.[25]
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.