Saif Turki Saif Turki - 7 months ago 11
Javascript Question

Execute only the last ajax request

I want to validate a field using jQuery ajax and php.

When I start taping more then 3 characters it send the request to php file but my problem is when I tap 3 valid characters and the 4th is invalid I must wait for executing the request 4 times.

I want to execute only the last request and kill the other pending request

I tried:

xhr = $.ajax(//...);
xhr.abort();


and

if(typeof xhr !== 'undefined')
xhr.abort();
xhr = $.ajax(//...);


but it doesn't work

This is my code:

// Check validation errors
var minLength = 3;
$('input[name^="data"][type=text]').on('keyup', function(){
var input = $(this);
var value = $.trim(input.val());
var url = input.data('url');
var div = input.parent();
var serialized = input.serialize();
if(value.length >= minLength){
$.ajax({
type: 'POST',
url: url+'.json',
data: serialized,
dataType: 'json',
success: function(data){
var error = data.error;

if(error){
div.removeClass('valid').addClass('invalid');
}else{
div.removeClass('invalid').addClass('valid');
}
}
});
}
});

Answer

something you could try, dont send the request if another key is pressed within a time period:

var minLength = 3;
var time_out_id=0;
$('input[name^="data"][type=text]').on('keyup', function(){
    var input = $(this);
    var value = $.trim(input.val());
    var url = input.data('url');
    var div = input.parent();
    var serialized = input.serialize();
    if(value.length >= minLength){

        if(time_out_id != 0) clearTimeout(time_out_id);

        time_out_id = setTimeout(function(){

            time_out_id=0;
            $.ajax({
                type: 'POST',
                url: url+'.json',
                data: serialized,
                dataType: 'json',
                success: function(data){
                    var error = data.error;

                    if(error){
                        div.removeClass('valid').addClass('invalid');
                    }else{
                        div.removeClass('invalid').addClass('valid');
                    }
                }

            });

        }, 250);

    }
});

This wont send a request until 250ms has past since the last keypress.