The XMLHttpRequest Object / XML Requests via JavaScript With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts might request pages, or send data to a server in the background. By using the XMLHttpRequest object, a web developer can change a page with data from the server after the page has loaded. Creating an XMLHttpRequest Object For Mozilla, Firefox, Safari, Opera, and Netscape: var xmlhttp = new XMLHttpRequest() For Internet Explorer: var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") -------------------------------------------------------------------------------- Creating an XMLHttpRequest Object Example (cross browser): <script type="text/javascript"> var xmlhttp var xmlhttpfunction loadXMLDoc(url) { //function loadXMLDoc(url) { xmlhttp = null // code for Mozilla, etc. if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() } // code for IE else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") } if (xmlhttp!=null) { xmlhttp.onreadystatechange = xml.state_change xmlhttp.open("GET",url,true) xmlhttp.send(null) } else { alert('browser does not support XMLHTTP') } } function xml.state_change() { if (xmlhttp.readyState==4) { // if xmlhttp shows "loaded" if (xmlhttp.status==200) { // if "ok" ;//... } else { alert('problem retrieving XML data') } } } </script> Dynamic Usage within HTML <html> <script> ... document.getElementById('x1').innerHTML = xmlhttp.status document.getElementById('x2').innerHTML = xmlhttp.statusText document.getElementById('x3').innerHTML = xmlhttp.responseText </script> <body onload="loadXMLDoc('note.xml')"> <span id="x1"></span> <span id="x2"></span> <span id="x3"></span> </body> </html> Note: An important property in the example above is the onreadystatechange property. This property is an event handler which is triggered each time the state of the request changes. The states run from 0 (uninitialized) to 4 (complete). By having the function xmlhttpChange() check for the state changing, we can tell when the process is complete and continue only if it has been successful. All the examples here use the async mode (the third parameter of open() set to true). The async parameter specifies whether the request should be handled asynchronously or not. True means that script continues to run after the send() method, without waiting for a response from the server. false means that the script waits for a response before continuing script processing. By setting this parameter to false, you run the risk of having your script hang if there is a network or server problem, or if the request is long (the UI locks while the request is being made) a user may even see the "Not Responding" message. It is safer to send asynchronously and design your code around the onreadystatechange event! -------------------------------------------------------------------------------- Notes From: http://www.w3.org/TR/XMLHttpRequest/ Use setRequestHeader() after open() and before send(). The send() flag is only relevant when the state is open (readyState=1). Even when async is set to false the readystatechange event will still be dispatched. For the send() method, if data is a DOMString, data must be encoded as UTF-8 for transmission. If data is a DOCUMENT, data must be serialized into a namespace well-formed XML document and encoded using the encoding given by data.xmlEncoding, if specified, or UTF-8 otherwise. If this fails because the document cannot be serialized user agents must act as if data was null. If data is not a DOMString or DOCUMENT, the stringification mechanisms of the host language must be used on data and the result must be treated as if data is a DOMString. Invoking send() without the data argument must give the same result as if it was invoked with null as argument. Scripts should specify the Content-Type header via setRequestHeader before invoking send() with an argument. If the argument to send() is a Document and no Content-Type header has been set user agents must set it to application/xml for XML documents and to the most appropriate media type for other documents (using intrinsic knowledge about the document). If the response is an HTTP redirect (status code 301, 302, 303 or 307), then it must be transparently followed (unless it violates security, infinite loop precautions or the scheme isn't supported). Once the request has been successfully acknowledged the state must be set to sent. Immediately before receiving the message body (if any), the state must be set to to receiving. When the request has completed loading, the state must be set to loaded. -------------------------------------------------------------------------------- Another function to return a cross-browser XMLHTTP Object: function getXMLHttpObj(){ if(typeof(XMLHttpRequest)!='undefined') return new XMLHttpRequest(); var axO=['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'], i; for(i=0;i<axO.length;i++) try{ return new ActiveXObject(axO[i]); }catch(e){} return null; } -------------------------------------------------------------------------------- XMLHttpRequest Object Methods abort() Cancels the current request. getAllResponseHeaders() Returns the complete set of http headers as a string. getResponseHeader("headername") Returns the value of the specified http header. open(method, "URL") open(method, "URL", async) open(method, "URL", async, "username") open(method, "URL", async, "username", "password") Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "PUT" (use "GET" when requesting data and use "POST" when sending data (especially if the length of the data is greater than 512 bytes. The URL parameter may be either a relative or complete URL. The async parameter specifies whether the request should be handled asynchronously or not. true means that script processing carries on after the send() method, without waiting for a response. false means that the script waits for a response before continuing script processing. User agents MUST at least support the following methods ([RFC2616]): GET, POST, HEAD, PUT, DELETE, OPTIONS When null is passed for either user or password user agents must act as if the relevant data (the user name or password) is not provided. send(content) Sends the request. setRequestHeader("label","value") Adds a label/value pair to the http header to be sent. The list of request headers must be reset when the open() method is invoked. Use setRequestHeader() after open() and before send(). XMLHttpRequest Object Properties onreadystatechange An event handler for an event that fires at every state change. readyState Returns the state of the object: 0 = uninitialized (The initial value) 1 = loading (The open() method has been successfully called) 2 = loaded (The user agent successfully acknowledged the request) 3 = interactive (Immediately before receiving the message body (if any). All HTTP headers have been received) 4 = complete (The data transfer has been completed) When readyState changes value a readystatechange event is dispatched on the XMLHttpRequest object, thus a callback function should be invoked. responseText Returns the response as a string responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties. responseXML is only available if the server sends back an XML document with MIME type text/xml, and not if it sends back, for instance, an HTML document. status Returns the status as a number (e.g. 404 for "Not Found" or 200 for "OK"). If server does not respond (properly), IE returns a WinInet Error Code (e.g 12029 for "cannot connect"). MSKB: 193625. statusText Returns the status as a string (e.g. "Not Found" or "OK"). ---------------------------------------- responseBody The responseBody property is read-only and represents the response entity body as an array of unsigned bytes, namely a SAFEARRAY of type VT_ARRAY | VTUI1. This contains the raw, uncoded bytes as received from the server. So, depending on the server, this may appear as binary-encoded data (UTF-8, UCS-2, UCS-4, shiftJis, etc). responseStream This property represents the response entity body as an IStream. This stream returns the raw, uncoded bytes as received from the server. Depending on the server, this may appear as binary-encoded data (UTF-8, UCS-2, UCS-4, shiftJis, etc). -------------------------------------------------------------------------------- Reusing XMLHttpRequest Object in IE In IE, if the open method is called after setting the onreadystatechange callback, there will be a problem when trying to reuse the XHR object. To be able to reuse the XHR object properly, use the open method first and set onreadystatechange later. This happens because IE resets the object implicitly in the open method if the status is 'completed'. For more explanation of reuse: Reusing XMLHttpRequest Object in IE. The downside to calling the open method after setting the callback is a loss of cross-browser support for readystates. See the quirksmode article. Reusing XMLHttpRequest Object in IE http://keelypavan.blogspot.com/2006/03/reusing-xmlhttprequest-object-in-ie.html quirksmode article http://www.quirksmode.org/blog/archives/2005/09/xmlhttp_notes_r_2.html -------------------------------------------------------------------------------- Microsoft Internet Explorer Caching and Prevention It is important to note that these techniques should be used only if the caching is inappropriate, otherwise, allow the caching. Setting the "Expires" header to reference a date in the past will avoid caching of the response. Here is an example in PHP. header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); // disable IE caching header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" ); header( "Cache-Control: no-cache, must-revalidate" ); header( "Pragma: no-cache" ); Alternatively, it is possible to force the XMLHttpRequest object to retrieve the content anyway, as shown in this example: req.open( "GET", "xmlprovider.php" ) req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ) //Previous line doesn't work. req.send( null ) Another method is to add a random string on the end of the url in the query: req.open( "GET", "xmlprovider.php?sid=" + Math.random())