Custom HTTP Headers
Custom HTTP Headers in AJAX Requests
The body of your AJAX requests will typically contain the core data of the request, such as information to be added to a database or search query parameters. It is still vital to communicate to the server request "metadata", or additional information about the request, and this can be achieved with HTTP headers.
The XMLHttpRequest object provides a mechanism to set custom request headers, and get the headers of the server's response. The setRequestHeader method handles setting custom request headers:
xhrobj.setRequestHeader(header_name, value);
Two methods provide the response headers:
document.write(xhrobj.getAllResponseHeaders);
/* Returns e.g.:
Date: Sat, 10 May 2008 01:00:00 GMT
Server: Apache/2.2.4 (Win32) PHP/5.2.1
Last-Modified: Fri, 16 May 2008 22:58:57 GMT
Content-Length: 11
Content-Type: text/plain */
xhrobj.getResponseHeader(headername);
alert(xhrobj.getResponseHeader("Date"));
// Will alert e.g. "Sat, 10 May 2008 01:00:00 GMT"
Adding an X-Requested-With header
To identify to the request that an AJAX request is taking place, it is common practice to add an X-Requested-With header with the value "XMLHttpRequest". This can be easily achieved in XMLHttpRequest:
// ...
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
This can then be checked on the server side, either through scripting or at server level.
| « Error Checking | AJAX Security Restrictions » |
More AJAX Tutorials:
» The obligatory 'My Ajax Tutorial' Post
» A Designer's Guide to Prototyping Ajax
» AJAX and PHP Form Processing
» AJAX Accessibility for Websites
» Ajax Wireframing Approaches
» Getting Started with AJAX in jQuery


