简体   繁体   中英

How to check whether an ajax request has allready been sent with Jquery?

I am using an Ajax request to post a form with Jquery.

$.ajax( 
        { 
            type: "POST", 
            url: "login.php", 
            data: $("#signin").serialize(),
            dataType: "json",
            cache: false,
            success: function(data, textStatus) {
                if (data.redirect) {
                    window.location.replace(data.redirect);
                }
                else {
                    $('#some').fadeOut(200);
                    $('#some2').fadeIn(200);
                    $("#some3").html(data.form);
                    $("#some").delay(2000).fadeOut(200);
                    $('#some2').delay(2800).fadeIn(300);
                }
            }           
        });

Now the ajax request will take place as soon as you click on a button "Login". The problem now is that if you press the button more than once the else case will be executed several times which will cause #some, #some2 and #some3 to fade out and in several times. So how could I check whether the request has allready been sent (without having to write something into my db)?

Make boolean flag, say, login_in_process , on login check this flag in true value. And check this flag on every click if it true then make empty return. In success and error callbacks set it in false state.

You can use a boolean value to record whether or not it has been clicked:

var loginClicked = false;

$('input_button_element').click(function(){
  if (!loginClicked) {
    loginClicked = true;
    // your js here - you may want to add some visual feedback to the user also
  }
});

you can make a global var

var loginClick = false;

Inside your method you first check that value

if (!loginClick) {
  loginClick = true;
  //your ajax code;
}

From here :

You can use .one() method and set it again in ajax callback.

function doAjax(){
    // Your Ajax call.
    $.ajax({..., complete: function() {
        // Ajax call done, re-enabling the button/link
        $("#buttonId").one('click', doAjax);
    }, ...});
}

$("#buttonId").one('click', doAjax);

You will have to store a boolean in a global scope, eg one stored on the window object:

if (!window.isClicked) {
    window.isClicked = true;
    ...Do your ajax call here        
}

Remember to ALWAYS restore the value of window.isClicked, not only in the success callback of ajax():

var jqxhr = $.ajax( ... )
.done(function() {  })
.fail(function() {  })
.always(function() { window.isClicked = false });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM