- Initializing an AJAX Application
- Sending a GET Request
- Sending a POST Request
- Sending a Synchronous Request
- Receiving Multiple Data from the Server
- Aborting an HTTP Request
- Retrieving HTTP Headers
- Receiving XML from the Server
- Using JSON for Data (De)Serialization
- Creating a Waiting Screen
- Solving the Bookmark Problem
- Solving the Back Button Problem
- Using XSLT
- Using an XML Library
- Using the Yahoo! Web Service
Aborting an HTTP Request
XMLHttp.abort();
Depending on the browser, only a limited number of HTTP requests can be done at a time. Especially if you have a page with multiple AJAX components (the modern term for this is "mashup"), you may run into trouble. Therefore, aborting an HTTP request may become a necessity.
The method used for that is abort(). The following code aborts the request if it has not been fully executed after five seconds. To demonstrate this behavior, the PHP script delay.php that is called by the code takes 10 seconds to execute. Also note that the readyState property is checked first: if it is 0 or 4, there is nothing to abort.
Aborting an HTTP Request (xmlhttpabort.html)
<script language="JavaScript" type="text/javascript" src="xmlhttp.js"></script> <script language="JavaScript" type="text/javascript"> var XMLHttp = getXMLHttp(); XMLHttp.open("GET", "delay.php?" + Math.random()); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.send(null); window.setTimeout("timeout();", 5000); function handlerFunction() { if (XMLHttp.readyState == 4) { window.alert("Returned data: " + XMLHttp.responseText); } } function timeout() { if (XMLHttp.readyState != 4 && XMLHttp.readyState != 0) { XMLHttp.onreadystatechange = function() { }; XMLHttp.abort(); window.alert("Request aborted"); } } </script>
Five seconds after loading this page, the request is aborted.