Chris
Chris

Reputation: 6233

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)?

Upvotes: 0

Views: 553

Answers (5)

Kamyar
Kamyar

Reputation: 18797

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);

Upvotes: 0

AndVla
AndVla

Reputation: 713

you can make a global var

var loginClick = false;

Inside your method you first check that value

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

Upvotes: 0

jkgeyti
jkgeyti

Reputation: 2404

You will have to store a boolean in a global scope, e.g. 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 });

Upvotes: 0

LeonardChallis
LeonardChallis

Reputation: 7783

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
  }
});

Upvotes: 0

Denis Ermolin
Denis Ermolin

Reputation: 5546

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.

Upvotes: 0

Related Questions