XMLHttpRequest?A method of making HTTP requests between a client and a server without the need for a page refresh. It's the X in Ajax.
XMLHttpRequest AdvantagesXMLHttpRequest Syntax
var xhr = new XMLHttpRequest(); // Create a new object
var data = 'field1=value1&field2=value2'; // URL-encoded data string
// Define our readystatechange handler
var readyStateHandler = function(event){
if( this.readyState == 4){
// handle this.responseText or this.responseXML
}
}
xhr.open('GET','/processing_script') // open a connection
xhr.onreadystatechange = readyStateHandler // set the handler
xhr.send(data); // send the data
XMLHttpRequest Limitations'field1=value1&field2=value2' (For real?)Subject to Same Origin Policy: same protocol, domain or IP, and port
document.domain.XMLHttpRequest, Level 2All of the advantages of
XMLHttpRequest + more goodies
FormData syntax for sending information| IE8 | IE9 | FF | FFMo | Safari | iOS Safari | Chrome | And. Webkit | Opera | OperaMo | |
|---|---|---|---|---|---|---|---|---|---|---|
XHR1 |
√ | √ | √ | √ | √ | √ | √ | √ | √ | √ |
timeout |
√ | √ | x | x | x | x | x | x | x | x |
| Cross-origin | ~ | ~ | √ | √ | √ | x | √ | √ | x | x |
withCredentials |
x | x | √ | √ | √ | x | √ | √ | x | x |
FormData |
x | x | √ | √ | √ | x | √ | √ | x | x |
ProgressEvents |
x | x | √ | √ | √ | x | √ | √ | x | x |
overrideMimeType() |
x | x | √ | √ | √ | √ | √ | √ | x | x |
For details by version, see CanIUse.com. (Android data is for Android 3.0+)
Internet Explorer supports a proprietary XDomainRequest object instead of cross-domain XHR.
Support for XHR.upload depends on whether or not the platform supports uploads (iOS does not).
var makeRequest = function(event){
event.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onload = function(event){ // process the response }
xhr.ontimeout = function(event){ alert('Request timed out.'); }
xhr.open('GET', 'bookmarks.json');
xhr.timeout = 5000; // timeout in milliseconds. 5000ms = 5s
xhr.send();
}
window.addEventListener('load', makeRequest, false);
(Try Internet Explorer 8 or 9)
FormData objectsvar xhr = new XMLHttpRequest();
var data = new FormData();
data.append('key','value');
data.append('name','Jane Doe');
xhr.open('GET','/processor');
xhr.send(data);
field1=value1&field2=value2multipart/form-data encoding (Hello, binary uploads!)
(use Chrome, Firefox, or Safari 4+)
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append('file',form['upload'].file[0]); // get file data*
xhr.open('GET','/processing_script');
xhr.send(data);
(use Chrome, Firefox, or Safari 4+)
form['upload'].file[0]: FileList interface from the File API, a class definition for the HTML5 file input type. files[0]), or the items attribute syntax (files.item(0))Applies to both the XMLHttpRequest and XMLHttpRequestUpload objects
| attribute | type | Explanation | Applies To |
|---|---|---|---|
onloadstart |
loadstart |
When the request starts. | Both |
onprogress |
progress |
While loading and sending data. | Both |
onabort |
abort |
When the request has been aborted, whether by invoking the abort() method or navigating away from the page. |
Both |
onerror |
error |
When the request has failed | Both |
onload |
load |
When the request has successfully completed. | Both |
ontimeout |
timeout |
When the author specified timeout has passed before the request could complete. | Both |
onloadend |
loadend |
When the request has completed, regardless of whether or not it was successful. | Both |
onreadystatechange only applies to XMLHttpRequest.
addEventListener() syntaxxhr.onprogress = function(event){ /* do something */ }
var progressHandler = function(event){ /* do something */ }
xhr.addEventListener('progress',progressHandler,false);
XMLHttpRequestUpload ObjectPart of the XMLHttpRequest interface.
XMLHttpRequestXMLHttpRequest.uploadvar xhr = new XMLHttpRequest();
var data = new FormData();
data.append('file',form['upload'].file[0]);
xhr.upload.onprogress = function(event){
console.log( event.loaded / event.total );
}
xhr.upload.onerror = function(event){ alert('something went wrong!'); }
xhr.upload.onload = function(event){ alert('file uploaded!'); }
xhr.open('GET','/processing_script');
xhr.send(data);
May be a lag between when the upload completes (when the load or loadend events are fired) and when the server returns a response.
Look just like same-origin requests, but uses full URLs.
xhr.open('GET','http://datahost.example/data.xml');
| Response Headers | Request Headers (browser set) |
|---|---|
| Access-Control-Allow-Origin | Origin |
| Access-Control-Allow-Credentials | Access-Control-Request-Method |
| Access-Control-Expose-Headers | Access-Control-Request-Headers |
| Access-Control-Max-Age | |
| Access-Control-Allow-Methods | |
| Access-Control-Allow-Headers |
Access-Control-Allow-OriginAccess-Control-Allow-CredentialsAccess-Control-Expose-HeadersAccess-Control-Max-AgeAccess-Control-Allow-MethodsGET, POST, PUT, HEAD, DELETE — are allowed. Access-Control-Allow-HeadersX-CustomHeader).Minimum header necessary for a cross-origin request to succeed.
HTTP/1.1 200 OK
Date: Fri, 27 May 2011 21:27:14 GMT
Server: Apache/2
Last-Modified: Fri, 27 May 2011 19:29:00 GMT
Accept-Ranges: bytes
Content-Length: 1830
Keep-Alive: timeout=15, max=97
Connection: Keep-Alive
Content-Type: application/xml; charset=UTF-8
Access-Control-Allow-Origin: *
Varies by server type and programming language, but here is a roundup:
Header set Access-Control-Allow-Origin "http://foo.example"setenv.add-response-header = ( "Access-Control-Allow-Origin" => "http://foo.example" )add_header Access-Control-Allow-Origin http://foo.example<add name="Access-Control-Allow-Origin" value="*" />print "Access-Control-Allow-Origin: http://foo.example"header("Access-Control-Allow-Origin: http://foo.example");response and responseType attributesresponseText (for text-based responses) and responseXML (for XML documents and fragments) are still supportedresponseType isn't yet supported in any browser(spec is still in flux)overrideMimeType()
var makeRequest = function(event){
event.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onload = function(event){
var xhr = event.target;
console.log(xhr.response); // the response.
}
xhr.open('GET', 'bookmarks.json');
xhr.send();
}
window.addEventListener('load', makeRequest, false);
overrideMimeType()Enforce a MIME type for the response. In this case, the browser will treat data.xml as XML despite its text/html content type.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.xml');
xhr.overrideMimeType('application/xml')
xhr.send();
Date: Sat, 04 Jun 2011 03:11:31 GMT Server: Apache/2.2.17 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html; charset=UTF-8
For more on XMLHttpRequest, Level 2 and associated technologies, see: