Sunil Kumar
Sunil Kumar

Reputation: 29

How to bind click event after unbind in jquery

I want to unbind click event of button until ajax call completes.

It unbinds click but I am not able to make it rebind click.

Below is my Ajax Call:-

   $("#btnsearch").click(function (event) {        
            $('#btnsearch').text('Wait...').unbind('click');
            $.ajax({
                url: "//api/Ulyx/OrderDetails",
                type: "GET",
                dataType: "json",
                beforeSend: function () {               
                },
                async: false,           
                },
                crossDomain: true,
                complete: function (data) {                 
                    $('#btnsearch').text('Search').bind('click');                  
                }
            });

Upvotes: 0

Views: 181

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Rather than binding/unbinding events, you could simply store a state variable to say that an AJAX request is in progress to disallow the sending of another one:

$("#btnsearch").click(function(event) {
  if (!$(this).data('ajax-in-progress')) {
    $(this).text('Wait...').data('ajax-in-progress', true);

    $.ajax({
      url: "//api/Ulyx/OrderDetails",
      type: "GET",
      dataType: "json",
      crossDomain: true,
      complete: function(data) {
        $('#btnsearch').text('Search').data('ajax-in-progress', false);
      }
    });
  }
});

Also note that I removed the async: false setting as it's very bad practice, and I fixed the syntax issues with the call, which I presume were just caused when copying the code to the question.

Upvotes: 1

Related Questions