XMLHttpRequest

 

ATTENTION: THIS PAGE IS Valid HTML 5 AND IS BEST VIEWED WITH HTML 5 - Please upgrade your browser or download one of the HTML 5 compatible browsers such as Mozilla Firefox, Chrome, Opera or IE 9 (March 14, 2011 or later). For more information see HTML 5 browsers.


If you find this helpful, please click the Google +1 Button to the left, if it is white, to make it turn blue or red. Thank you! (It also helps find this page again more easily.)


PDF mobile

JavaScript XMLHttpRequest

XMLHttpRequest is a JavaScript object type that can be used to retrieve a resource via a URL. Despite the Http in the name of the type, an XMLHttpRequest object can be used to retrieve resources via various protocols including the

  • http,
  • ftp, and
  • file protocols.

First, create an instance of XMLHttpRequest:

var req = new XMLHttpRequest();

Add any necessary event listeners to the request:

req.addEventListener("load", function(ev){alert("status=" + req.status);});
req.addEventListener("error", function(ev){alert("handle error");});
  • If you attempt to access status or statusText when readyState is not DONE you will get an INVALID_STATE_ERR DOM Exception 11 error. In any event other than load or error, which are only called when readystate is DONE, be sure to do if (req.readyState == 4) before checking req.state or req.readyState.
  • If the destination site is a different domain than the origin, you need to add headers at the destination site to avoid errors such as XMLHttpRequest cannot load ... with Origin http://www.origin.com is not allowed by Access-Control-Allow-Origin or Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
  • In addition, when the destination is different from the origin, the only status that is returned is 200 OK; otherwise the req.status is zero, even when an HTTP error such as 404 Not Found has occurred.

To send a GET request:

var url = "http://www.ExampleOnly.com/demo/env.php?query&param=value";
req.open("GET", url, true);
req.send(null);
  • In the third parameter of req.open, specify true for an asynchronous request or false for a synchronous request

To send a POST request:

var url = "http://www.ExampleOnly.com/demo/env.php;
req.open("POST", url, true);
var formData = new FormData();
formData.append("param", "value");
req.send(formData);
  • In the third parameter of req.open, specify true for an asynchronous request or false for a synchronous request

Valid HTML 5