简体   繁体   中英

jQuery Allow only one click before .ajax()

I am trying to allow a button to be clicked only once and then some data be submitted via ajax. The problem I am facing is that a user can click 50x and the data is POST submitted each time?

jQuery("#id").unbind('click');

jQuery.ajax({
    type: "POST",
    url: ajax_url,
    data: ajax_data,
    cache: false,
    success: function (html) {
        location.reload(true);
    }
});

How can I ensure that if a user clicks #ID 100x - that the data is only submitted once? And then #ID is re-enabled?

You could use the .one() function in jQuery.

jQuery("#id").one('click', function()
{
    jQuery.ajax({
        type: "POST",
        url: ajax_url,
        data: ajax_data,
        cache: false,
        success: function (html) {
            location.reload(true);
        }
    });
});

Bear in mind this will completely remove the click event, even if you have an error with your ajax, you still won't able to click it again.

just disable the button

$("#id").attr("disabled", "disabled")

and then in the success function enable it

$("#id").removeAttr("disabled")

Easiest way would be to use a flag which gets reset when the success is fired:

if(clicked == False){
    clicked = True;
    jQuery("#id").unbind('click');

    jQuery.ajax({
       type: "POST",
       url: ajax_url,
       data: ajax_data,
       cache: false,
       success: function (html) {
           location.reload(true);
           clicked = False;
       },
       error: function () {
            alert("Error happened");
           clicked = False;
       }
    });
}

You can disable to control, or use one of the many modal libraries to show the spinning wheel

see this Jquery modal dialog question on SO

You could disable the button on click event and enable it back when ajax request is completed.

In your click event you could disable the button and then re-enable the button in the success function of the ajax event.

Another option would be to set a parameter on the element that is being clicked to indicate the button was clicked and then check to see if it is set if it is don't send the ajax request if not then do send it. Once the ajax is done you can unset the parameter again to allow it to be run.

try this:

$(document).ajaxStart({ function() {
 $('#submit_button').click(function(){
   return false;
 });
});

where: #submit_button is id of the element U want to disable

that code will disable clicking on the submit button

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