Ajax, prevent multiple request on click

前端 未结 10 2180
忘掉有多难
忘掉有多难 2020-11-28 04:10

I\'m trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn\'t work. Just the first time works fine, then return fals

相关标签:
10条回答
  • 2020-11-28 05:02

    I have also faced a similar problem.

    Just adding $('#do-login').attr("disabled", true); gives me the solution.

    $('#do-login').click(function(e) {
       e.preventDefault();
       $('#do-login').attr("disabled", true);
       .........
       .........
    

    Here do-login is button id.

    0 讨论(0)
  • 2020-11-28 05:05

    Or you can do it by $(this).addClass("disabled"); to you button or link and after click is performed, you can $(this).removeClass("disabled");.

    // CSS

    .disabled{
    cursor: not-allowed;
    
    }
    

    // JQUERY

    $('#do-login').click(function(e) {
       e.preventDefault();
    
        $(this).addClass("disabled");
        $.ajax({
            type: "POST",
            url: "/php/auth/login.php",
            data: $("#login-form").serialize(),
            context: this,
            success: function(msg) {
        //do more here
    
               $(this).removeClass("disabled");
            },
        });
    });
    

    P.S. If you use bootstrap css, you do not need the css part.

    0 讨论(0)
  • 2020-11-28 05:05

    for prevent multiple ajax request in whole site. For example: If use ajax request in other ajax page, Using ajax in php loop, etc, Give you multiple ajax request with one result. I have solution:

    Use window.onload = function() { ...  } 
    

    instead of

    $(document).ready(function(){ ...  });
    

    on the main index.php page. Its will be prevent all multi request. :)

    0 讨论(0)
  • 2020-11-28 05:06

    Use on() and off(), that's what they are there for :

    $('#do-login').on('click', login);
    
    function login(e) {
        e.preventDefault();
        var that = $(this);
        that.off('click'); // remove handler
        $.ajax({
            type: "POST",
            url: "/php/auth/login.php",
            data: $("#login-form").serialize()
        }).done(function(msg) {
            // do stuff
        }).always(function() {
            that.on('click', login); // add handler back after ajax
        });
    }); 
    
    0 讨论(0)
提交回复
热议问题