jQuery Allow only one click before .ajax()

Tom picture Tom · Jun 12, 2011 · Viewed 8.5k times · Source

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 ?

Answer

MacMac picture MacMac · Jun 12, 2011

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.