Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consecutive Ajax calls

I need a little help in my application design. Using Ajax I want to get some PHP resources consecutively but I don't think if it is good to retrieve them using JQuery $.ajax method.

I think something like this means wrong design:

$.ajax({
     url: SERVERURL+'index.php/home/checkAvailability',
     datatype: 'text',
     success: function(data){
        if(data == 'unavailable'){
           // do stuff
        }
        else{
           $.ajax({
              url: SERVERURL+'index.php/home/getWebTree/',
              dataType: 'json',
              success: function(data){
                 // do stuff
              }
           });
        }
     }
  });

Can anybody give me a suggestion to get a better design? How can I do the same in a better way?

Thanks!

EDIT: like @arnorhs tell us, using async parameter could be a solution. But I'm still think that there are other solutions instead of using consecutive ajax calls.

EDIT2: checkAvailability and getWebTree are PHP functions using CodeIgniter that I've developed to get resources from an external server using Http_Request object.

function checkAvailability() {
      $this->load->library('pearloader');
      $http_request = $this->pearloader->load('HTTP', 'Request');
      $http_request->setURL('http://myurl');
      $http_request->_timeout = 5;
      $http_request->sendRequest();
      $res = 'available';
      if (!$http_request->getResponseCode())
         $res = 'unavailable';
      return $res;
   }
like image 481
Fran Verona Avatar asked Feb 22 '11 19:02

Fran Verona


People also ask

How do I stop multiple Ajax calls from repeated clicks?

}); If isLoading is false, the AJAX call starts, and we immediately change its value to true. Once the AJAX response is received, we turn the value of that variable back to false, so that we can stop ignoring new clicks.

How do you handle concurrent AJAX requests?

This is done by using JavaScipt closures. Functions can be written to handle such requests. Parameters can be passed to an appropriate function selected by closures.

Can we execute run multiple Ajax requests simultaneously in jQuery?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.

What happens when one Ajax call is still running and you send an another Ajax call before the data of first AJAX call comes back?

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.


3 Answers

Doing the calls all the same time

If you want to do all the ajax calls at the same time, you can simply call an ajax request right after the others. You could even assign them the same success handler. If you want a more "elegant" approach, I would do something like this:

// define a set of requests to perform - you could also provide each one
// with their own event handlers..
var requests = [
    { url: 'http://someurl', data: yourParams   },
    { url: 'http://someurl', data: yourParams   },
    { url: 'http://someurl', data: yourParams   },
    { url: 'http://someurl', data: yourParams   }
];

var successHandler = function (data) {
    // do something
}

// these will basically all execute at the same time:
for (var i = 0, l = requests.length; i < l; i++) {
    $.ajax({
        url: requests[i].url,
        data: requests[i].data,
        dataType: 'text',
        success: successHandler
    });
}

.

Do a single request

I don't know your use case, but of course what you really should be trying to do is retrieve all the data you're retrieving in a single request. That won't put a strain on your server, the site/application will seem faster to the user and is a better long term approach.

I would try to combine checkAvailability and getWebTree into a single request. Instead of receiving the data in Javascript as text objects, a better approach would be to receive them as json data. Luckily PHP provides very easy functions to convert objects and arrays to json, so you'll be able to work with those objects pretty easily.

edit: small modifications in the PHP code now that I understand your use case better.

So something like this in the PHP/CI code:

function getRequestData () {
    if (checkAvailability() == 'available') {
        $retval = array (
            'available' => '1',
            'getWebTree' => getWebTree()
        );
    } else {
        $retval = array (
            'available' => '0'
        );
    }   
    header('Content-type: text/javascript; charset=UTF-8');     
    echo json_encode($retval););
}

And the Javascript code can then access those by a single ajax request:

$.ajax({
    url: 'http://yoururl/getRequestData',
    dataType: 'json',
    success: function (jsonData) {
        // we can now access the parameters like this:
        if (jsonData.checkAvailability) {
            // etc
        }
        //and of course do something with the web tree:
        json.getWebTree
    }
});

.

Execute the requests synchronously

If you set the async parameter in the $.ajax options to false the functions will be made in a synchronous fashion so your code halts until execution has been completed.. or as the documentation says:

asyncBoolean

Default: true

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

See http://api.jquery.com/jQuery.ajax/

like image 175
arnorhs Avatar answered Oct 22 '22 13:10

arnorhs


If you really need to make two calls you can be more expressive with Deffered that was introduced in jQuery 1.5.

$.when(checkAvailability())
   .then(getWebTree())
   .fail(function(message){
       if(message === 'Not available!')
       {
           // do stuff
       }
   });

function checkAvailability(){
    var dfd = $.Deferred();

    $.ajax({
    url: SERVERURL+'index.php/home/checkAvailability',
    datatype: 'text',
    success: function(data){              
        if(data == 'unavailable'){
            dfd.reject("Not available!");
        }
        else{
           dfd.resolve();
        }
    }
    });

    return dfd.promise();
};

function getWebTree(){
    $.ajax({
        url: SERVERURL+'index.php/home/getWebTree/',
        dataType: 'json',
        success: function(data){
            // Do stuff
        }
    });
};

Check it out live at http://jsfiddle.net/jimmysv/VDVfJ/

like image 45
jimmystormig Avatar answered Oct 22 '22 14:10

jimmystormig


It sounds like you could make use of the deferred object that's new to jquery 1.5

http://api.jquery.com/category/deferred-object/

like image 3
ScottE Avatar answered Oct 22 '22 13:10

ScottE