1

I have button. Click this button send $.post() request and add item to basket. I want that if user clicks button fast ten times, it mustn't send 10 requests, but only one width count 10. code like this:

<div class='qty'>
<input type='text' id="qty" value='1'>
<a class='button' href='#'>add To Basket</a>

</div>

script:

$(document).ready(function(){

  $(".button").click(function(){

    var qty=$(this).parent().find(input[type='text']).val();

    $.post('/ajax.php', "qty="+qty, function(){
      $(this).parent().find(input[type='text']).val("1");

    });

  });

});
2
  • 2
    Don't build a query string yourself, pass an object to jQuery and let it do it for you. Commented Dec 19, 2012 at 19:11
  • Assuming you'll have more than one qty input, you can't use the same id for each of them. Commented Dec 19, 2012 at 19:16

5 Answers 5

2

This is a basic debouncing problem. Change <input id="qty"> to <input class="qty"> and:

$('.button').click(function(e) {
    var btn = $(this), qty = btn.parent().find('.qty');

    clearTimeout(btn.data('timeout'));

    qty.val(qty.val()+1);

    btn.data('timeout', setTimeout(doPost(qty), 1000));
});

function doPost(el) {
     return function() {
         $.post('/ajax.php', {qty:el.val()});
     }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I wouldn't call this debouncing in the strict sence of the word, since you actually want to register each push that occurred.
@WillemD'haeseleer, we're debouncing the requests, not the button clicks.
that's true ! i only just looked up what debouncing actually means and hadn't thought it trough, thx for teaching me something new !
2

You will need to save the the clicks in a variable and wait a short amount of time after each click before making the final post.
Here is an implantation example, each time the user clicks he has another 100 milliseconds to click again, which is then added to the total clicks. only the last click causes the post event to occur, after which the click is reset back to 0.
During the post the button is disabled to prevent further clicking.

$(document).ready(function(){
    var clicks = 0;
    var timeoutId = 0;
    // putting the post in a separate function prevents unnecessary closures 
    var doPost = function(){
        $(".button").attr("disabled", "disabled");
        $.post('/ajax.php', "qty="+clicks, function(){
            $(this).parent().find(input[type='text']).val("1");
            clicks = 0;
            $(".button").removeAttr("disabled");
        });
    };
    $(".button").click(function(){
        clearTimeout(timeoutId);
        timeoutId = setTimeout(doPost, 100);
        clicks++;
    });
});

Comments

0

You can setTimeout for some small time (e.g. 1 sec) in .button#onclick handler that will call for $.post() (instead of posting values directly). Timeout handler must be saved into variable globally to all .button#onclick executions. Additionally every .button#onclick execution must check if previos timeout is still active. If it is, kill old timeout and setup new one. If not, just setup new.

So every button click will kill old timeout and set new timeout. Only the last-click setTimeout code body will be executed.

Comments

0

What do you mean by "fast"? Probably you want to use a timer function like Underscore's debounce (if you don't want to include whole underscore, you can cut it out and use it standalone):

<div class='qty'>
   <input type='text' id="qty_num" value='1'>
   <a class='button' id="qty_add" href='#'>add To Basket</a>
   <output id="qty_out">0</output><label for="qty_out"> items in basket</label>
</div>
$(document).ready(function() {
    var count = 0;
    function send() {
        $.post('/ajax.php', {qty: count}, function(result){
            $("#qty_out").val(result);
        });
        count = 0; // reset
    }
    var sendAfterSecond = _.debounce(send, 1000); // here
    $("#qty_add").click(function(e) {
         var num = parseInt($("#qty_num").val());
         count += num;
         sendAfterSecond();
    });
});

Comments

-2
$(document).ready(function(){

    $(".button").click(function(){

    // disable the button
    $(this).attr("disabled", "disabled"); // if its a submit button

    var qty=$(this).parent().find(input[type='text']).val();

    // request some thing back in json {"success":1} or 0 if failed to add to cart.
    $.post('/ajax.php', "qty="+qty, function(m){ 
            if(m.success==1)
            {
                // enable the button
                $(".button").removeAttr("disabled"); // if its a submit button
            }

            $(this).parent().find(input[type='text']).val("1");
        },"json");

    });

});

1 Comment

this is not what the OP asked, this simply disables the button

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.