1
$('#email').keyup(function(){
    setTimeout(function(){   
        $.post('advert/crop.php', {
            email:form.email.value, password:form.password.value            
        },
        function(output){
            $("#output").empty().append("<img src='loading.gif'/>");
            setTimeout(function() {$('#output').html(output).fadeIn(50)}, 500);
        }); 
    }, 2000);
});

I have an input type text, I use jquery post and post back from php to check email already registered or pw too short.

I use keyup setTimeout for 2sec after, so while user typing, it will auto check.

My problem is if user type 3 words. it will post 3 times. is any way to solve this?

set up a timer only post every few sec after user finish typing

Ben
  • 2,562
  • 8
  • 37
  • 62

3 Answers3

2

Clear the timer whenever there is a keyup event so that only a single request is sent which will be the latest.

var timer;
$('#email').keyup(function(){
    clearTimeout(timer);
    timer = setTimeout(function(){   
        $.post('advert/crop.php', {
            email:form.email.value, password:form.password.value            
        },
        function(output){
            $("#output").empty().append("<img src='loading.gif'/>");
            setTimeout(function() {$('#output').html(output).fadeIn(50)}, 500);
        }); 
    }, 2000);
});
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
2
(function () { //to avoid any variable set on global scope, use a closure
    var timeout;
    $('#email').keyup(function () {
        clearTimeout(timeout); //clear your timeout here
        timeout = setTimeout(function () {
            $.post('advert/crop.php', {
                email: form.email.value,
                password: form.password.value
            },

            function (output) {
                $("#output").empty().append("<img src='loading.gif'/>");
                setTimeout(function () {
                    $('#output').html(output).fadeIn(50)
                }, 500);
            });
        }, 2000);
    });
})();
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

What you need is a keyup delay =) Basically its timer that is reset every keypress and only runs the post if the timer reaches its limit.

See this stackoverflow answer: How to delay the .keyup() handler until the user stops typing?

Community
  • 1
  • 1
azzy81
  • 2,261
  • 2
  • 26
  • 37