Javascript XMLHttpRequest, creation history, standards, examples

XMLHttpRequest (XHR) is an API in the form of an object provided by the JavaScript browser environment. In particular, finding data from XHR to constantly change a loaded webpage is a basic Ajax design concept. Despite the name, XHR can be used with protocols other than HTTP, and the data can be in the form of not only XML, but also JSON, HTML or plain text. WHATWG supports the XHR standard. The ongoing work at W3C to create a stable specification is based on snapshots of the WHATWG standard.

Javascript XMLHttpRequest ActiveX Object




Initially, Javascript XMLHttpRequest was an ActiveX object; its use was limited to Microsoft-based intranets and was not suitable for other sites. The Mozilla team became interested in implementing the JScript equivalent and distributed it to all browsers, including those based on Gecko / KHTML and Opera. Even IE7 no longer requires ActiveX to use XHR.

XMLHttpRequest History

The Javascript XMLHttpRequest concept was created by Outlook Web Access specialists for use on a Microsoft Exchange 2000 server. Versions 5 and 6 did not determine the XHR object identifier in their scripting languages, since the Request identifier itself was not standard at the time of release. Microsoft added an object identifier to its scripting languages ​​in Internet Explorer 7.0, released in October 2006. In the browser project, the Javascript XMLHttpRequest interface was developed and implemented in the Gecko layout engine.





It was modeled in such a way as to be as similar as possible to the Microsoft Request interface. Mozilla created a wrapper to use this interface through a JS object called XMLHttpRequest. The object was already made available in Gecko version 0.6, released on December 6, 2000, but it was not fully functional until version 1.0 of Gecko was released on June 5, 2002, after which the object identifier became the de facto standard in other large web -systems:

  • Safari 1.2, released in February 2004.
  • Opera 8.0, released in April 2005.
  • iCab 3.0b352, released in September 2005.

With the advent of cross-browser JavaScript libraries such as jQuery, developers can invoke Javascript XMLHttpRequest functionality without encoding directly into the API. The Wide Web Consortium World published a draft specification for XMLHttpRequest on April 5, 2006 to document a minimal set of compatible functions based on existing implementations, allowing developers to use them without platform-specific code.

On February 25, 2008, the W3C also published another specification for its working draft, XMLHttpRequest Level 2. Level 2 consists of advanced functionality, including support for requests and processing of byte streams.

Object ID Standards

Since the W3C standard for the XMLHttpRequest Javascript post object is still a preliminary, user agents may not follow all the definition functions, and any of the following actions may be changed. Extreme care should be considered when writing a script with an XMLHttpRequest object for multiple user agents.









In HTTP and HTTPS, XMLHttpRequest object requests are initialized in an open way. It is called before the request is actually sent for verification. This method does not guarantee that the URL exists and that the user information is correct. It can take up to five parameters, but it only requires two to initialize the request. The first parameter is a text string. Introducing query methods that must be supported by the appropriate user agent defined by the W3C project for XMLHttpRequest Javascript. Examples:

  1. GET is supported by Internet Explorer 7, Mozilla.
  2. POST is supported by IE7, Mozilla.
  3. HEAD is supported by IE7.

Request methods are not limited to those listed above. The W3C project says that the browser can support them as it sees fit.

The second parameter is another text string that indicates the URL of the HTTP request.

The third parameter is a boolean that indicates whether the request will be asynchronous. It is not required by the W3C project. Its default value should be considered true using the appropriate W3C user agent.

An asynchronous true request will not wait for a server response before continuing with the current script. Instead, it will call the onreadystatechange event listener of the XMLHttpRequest Javascript post object at different stages of the request.

The fourth and fifth parameters are the username and password. These parameters can be provided for authentication and authorization, if required by the server.

SetRequestHeader Method

After successful initialization, you can call the Header method of the XMLHttpRequest open Javascript object to send HTTP headers with the request. The first parameter to the method is the name of the header. The second parameter is the value of the text string. This method should be used for each header that is sent with the request.

The hidden “stone” in the XMLHttpRequest standard, which simplifies the process of fetching and analyzing JSON data through Ajax, is JSON & JSON-P. The usual way to offer server data for browsers so that they can be used in client-side JavaScript is to format the data, such as JSON, and access it through its own URL. For example: XMLHttpRequest Javascript Json

To send an HTTP request, you must call the XMLHttpRequest send method.

Firefox 3.0.x and previous versions throw an exception if send is called without an argument. If this parameter is a DOM document object, the user agent must ensure that it is converted to well-formed XML.

If the Content-Type request header has not yet been added via SetRequestHeader, it should be automatically added by the corresponding user agent with the following action: “application / xml; charset = charset ”, where charset is the encoding used for the document. If the user agent is configured to use a proxy server, the XMLHttpRequest object will modify the request to pass the configured headers to the Proxy-Authorization.

XHR Status Changes

If the method was called successfully, the property of the XMLHttpRequest object will be set to 1 (Open). After the HTTP response headers have been received, the readyState property of the XHR is set to 2 (HEADERS_RECEIVED). After loading the contents of the HTTP response, the readyState property of the XHR must be set to 3 (Loading).

After the HTTP response has finished loading, the readyState property of the XHR must be set to 4 (Done). The listener will only respond to state changes that occur after it is determined. To detect states 1 and 2, the listener must be defined before calling open. The public method must be applied before calling send.

This method aborts the request if the readyState of the XHR has not yet become 4 (Done). The abort method ensures that the callback handler will not be called during an asynchronous request. Some AJAX libraries use interruption to undo potential duplicates or corrupt requests.

Cross Domain Requests

In the history of the early development of the Internet, it was discovered that it is possible to violate the security of users using JavaScript to exchange information from one website to another, less reputable. In this way, all modern browsers implement the same origin policy, which prevents many attacks, such as crossite scripting.

Javascript XMLHttpRequest onload data is subject to this security policy, but sometimes web developers want to deliberately circumvent restrictions. This is due to the legitimate use of subdomains, since the creation of XHR from the page formed by foo.example.com to obtain bar.example.com information from it usually fails.

There are various alternatives to circumvent this security feature, including JSONP, resource sharing (CORS), or alternatives with plugins such as Flash or Silverlight.

Programs in browsers

Initializing an XHR object is actually quite simple in most browsers, but to support MSIE 5 and 6, you need to serve several different methods, so the process looks so complicated. Basically, the script tries to consistently use three different methods until it succeeds or ends.

Initialization of the program in browsers




The loadXMLDoc function takes two parameters. The first one is the location of the script on the server side, and the second is the variables that need to be passed to this script.

This is a brief example of how to call a script. It uses a script located in /scripts/myscript.php with two GET parameters (q and target). It is recommended that you encode values ​​using encodeURIComponent.

POST instead of GET

To transfer data larger than 512 bytes to the server, you need to use POST or new XMLHttpRequest Javascript 34 Javascript xml instead of GET. If you need to receive POST data, you need to change the type of the MIME request using the Content-Type header and passing the variables in the send call. The final part of the loadXMLDoc function changes, as shown in the photo below.

Using POST instead of GET




In most cases, the third parameter to the open command can be stopped. A value of true indicates that the call should be asynchronous - the script continues without waiting for the XML response, which already exists by default. Passing a false value stops the script until a response is received.

The script referenced by the URL will be a server-side script (PHP, Perl or similar). It returns a well-formed XML document. To avoid browser security warnings, it must be located in the same domain as the calling page, and be accessible via HTTP or HTTPS.

Passing from JavaScript to a server-side script

A function that processes the response (for example, processReqChange) should be able to unpack and process the received XML. This diagram shows how data is transferred from JavaScript to the server script and vice versa.

The principle is pretty simple. The returned XML document will contain one or more commands that are executed sequentially - to generate alerts, to change form values, or to control the DOM. All this is done by the processReqChange function.

Available teams

In total, seven different commands are used that can be called by the object library:

  • alert (message) - display a JavaScript alert.
  • setvalue (target, value) - set the value of the form field with the identifier from the target.
  • setdefault (target) - reset the value of the form field.
  • focus (target) - set focus in the form field.
  • setcontent (target, content) - set the internal HTML of the HTML element.
  • setstyle (target, property, value) - set the style of the HTML element.
  • setproperty (target, property, value) - set the property of the HTML element.

In each case, the target is an identifier that refers to an element of the HTML page. Other values ​​are text or HTML to add additional parameters to the processReqChange function.

Generating an XML Response Using PHP

The functions presented here are intended for PHP programmers who do not want to know too much about JavaScript, because after sending the initial request, further JScript is not required. An XML file (it generates a warning message, for example, for the case when clicking on the link below creates a JS warning window with the text "hello world!") - this is an important first step in any programming language.

Generating an XML Response Using PHP




The following XML response will load some text into an element on the page. In this case, the output, which has the identifier 2, will be displayed in the div. Instead of a div, you can easily set the contents of the heading, paragraph, or table cell: example2 hello world.

example2 hello world




As mentioned earlier, you can embed HTML, not text, as well as return dynamic rather than static data. The following XML request is generated using PHP to insert the current date and time.

XML creation




Internet Explorer will cache the XML response and use it for future requests. This means that the conclusion will never change. Other browsers cause a new request each time.

All DOM-enabled browsers accept backgroundColor, because the style name has a background color that is more “correct” and only works in some of them. Values ​​can be generated on the fly using PHP or another server. The first command sets the background-color property in the hello world field to yellow (# ff0), and the second to random (red, green, or blue). Commands are mainly associated with the formation of fields - setting / resetting the value in the field and setting the focus. They are useful when checking the form on the server side in real time, when you need to view data without reloading the current page.

Creating XML Using JavaScript

There are several different ways to call the loadXMLDoc function. For example, a link to the form is taken as the first parameter, and then two additional variables.

A successful call to loadXMLDoc returns true. The OnSubmit handler will return false. Overriding the default action, it will present an event that would otherwise trigger the form. Further execution is done using Ajax, so the browser does not need to load a new page. A failed call to loadXMLDoc returns false. The OnSubmit handler will return "true", as a result of which the form will be submitted in normal mode. Further execution takes place using nonAjaxTarget.html.

ASCII character codes




The Javascript xmlhttprequest cookie response value caching function is executed. Some browsers will cache GET requests made using XHR so that after the first call, subsequent ones from the same script simply reload the first response. To get around this, you need to add a random line or timestamp to the request, as shown in the photo below:

GET Request Caching




If the script always returns the same answer for the given parameters, then there is no need to worry about this, since caching is used to speed up the application.

To summarize how easy it is to work with Ajax using this structure, you only need to do the following:

  • Configure a server-side script to accept GET or POST or COOKIE parameters and return a valid XML file.
  • Specify the xmlhttp.js JS file on the page.
  • Use JavaScript to call.

Ajax callbacks can be accomplished by instantiating an XHR object in client JScript. Javascript XMLHttpRequest get can be used to directly call server objects such as pages and web services. They will store or return data.

Ajax was originally an acronym for asynchronous JS and XML. “Asynchronous” means that several events occur completely independently of each other. Once the client initiates an Ajax callback for the server, it does not need to wait for a response, as it can continue to use the web application while processing the request. After that, the server will send a response to the client, and the client will process it as necessary.




All Articles