开发者

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 aj开发者_Python百科ax. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜