DELETE me
DELETE me

Reputation:

How to cancel JSON request when sending a new jsonrequest to server

When the user type something in textbox the auto-complete work with json, he make lots of requests to the server. How can I stop the old request when making a new request in jQuery?

Upvotes: 5

Views: 3970

Answers (2)

user57508
user57508

Reputation:

a first, basic, attempt would be: just make a small offset (eg. 100ms) for the request. so you just need to reset the timer each time a key is pressed.

eg.

var timeout;
var textBox = $('#textbox');
textBox.change(function() {
    if (timeout) {
        clearTimeout(timeout);
    }
    var callingMethod = /* insert your method for the request */;
    timeout = setTimeout(callingMethod, 100);
});

second attempt would be: the request should be a variable. each time you enter your request-logic check the variable against null (some kind of: double locking pattern). so if the variable is not null, you know that a request is going on. hence you store the old request in the variable you can cancel it.

eg.

var request;
function DoMagicThing() {
    if (request) {
        request.abort();
        request = null;
    }

    request = $.ajax({
        /* insert options here */,
        complete = function() {
            request = null;
        }
    });
}

Upvotes: 0

jAndy
jAndy

Reputation: 235982

I guess you fire those json request over a XMLHttpRequest object or in other words, you're using .ajax(). You can in general cancel an ajax request by using .abort().

var xhr = $.ajax({});

// somewhere else
if(xhr)
   xhr.abort();

since .ajax() returns the original XHR event you can store that somewhere and abort that request. Of course you would have to create somekind of "request logic" to handle this stuff. Example:

var xhrmanager = function() {
    var requests = [],
        self     = {};

    self.create  = function(params, cb){
        if(typeof params === 'object') {// additional checks here
           var xhr = $.ajax($.extend({
               url:      '/path/script.pl',
               dataType: 'json',
               type:     'GET',
               success:  function(data, status, req){
                    if(typeof cb === 'function')
                       cb.apply(this, [data]);                        
               },
               complete: function(req, status) {
                    var pos = $.inArray(req, requests);

                    if(pos > -1)
                       requests.splice(pos, 1)
               }
           }, params || {}));
        }
    };
    self.clearAll = function(){
        for(var i = 0, len = requests.length; i < len; i++){
           requests[i].abort();
        }
    };

    return self;
};

usage like:

var json_requests = xhrmanager();

json_requests.create({
   data:  'some=data'
}, function(data) {
   // do something
});

json_requests.clearAll();

Upvotes: 3

Related Questions