1. Home
  2. Computing & Technology
  3. JavaScript

Introduction to Ajax

13. Multiple Requests

clr gif

With our requests being asynchronous we are not waiting for one request to return a response from the server before being able to make another request. There is no reason why our visitor cannot initiate further requests to the server before the first request has returned a response. We do have to be a bit careful in how we code this though.

The one thing that we need to avoid is having the same request object used multiple times simultaneously. In the last tutorial we looked at how to avoid this by aborting the previous request if one exists prior to generating the new request. If we instead need to be able to leave that request running and start a new request then we need somewhat different code. Let's start by modifying our code so that we can handle multiple ajax requests more easily.

Now we can create our request object when it doesn't already exist and arrange to create a second request object if the first one does exist. What we do with the responses that we get back can be request dependedt or you may just want to call a common routine passing it whichever response that comes.

if (!ajaxObj) {
ajaxObj = XMLHttp();
ajaxObj.get('myrequest.php');
} else {
ajaxObj2 = XMLHttp();
ajaxObj2.get('myrequest.php');
}
ajaxObj.response = function() {
if (this.resp == 'xml') {
alert(this.responseXML);
} else if (this.resp == 'text') {
alert(this.responseText);
} else {
alert(this.resp);
}
}
ajaxObj2.response = function() {
if (this.resp == 'xml') {
alert(this.responseXML);
} else if (this.resp == 'text') {
alert(this.responseText);
} else {
alert(this.resp);
}
}

Simply replace the alert statements in the above code with whatever processing you wish to perform with XML, text, and errors respectively.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.