XMLHttpRequest

Source: Wikipedia, the free encyclopedia.

XMLHttpRequest (XHR) is a JavaScript class[a] 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.[b] 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

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] [c] 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.

parameters
, but requires only the first two.

var request = new XMLHttpRequest();

request.open( RequestMethod, SubmitURL, AsynchronousBoolean, UserName, Password );

* 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

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 ).[d]

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.[e] 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[f] and performance costs.[g] 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 does not 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.[h]

CGI server component

The server component of a CGI XMLHttpRequest is an

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/.[i]

  • 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

  • WebSocket
  • Representational state transfer
    (REST)

References

  1. . 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. ^ .
  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. ^ .
  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. .
  13. .
  14. ^ "XMLHttpRequest Standard; The constructor". Retrieved 2023-04-10.
  15. ^ .
  16. .
  17. ^ "HTTP Documentation". June 2022. Retrieved 2023-04-12.
  18. .
  19. ^ "XMLHttpRequest Standard; The open method". Retrieved 2023-04-12.
  20. .
  21. .
  22. ^ .
  23. ^ .
  24. . PHP is a server-side scripting language designed specifically for the Web.
  25. ^ a b "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. 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. declarative language
    constructs.
  7. 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]

External links