Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account