tags:

views:

143

answers:

3

I have "a" element which servers as button. It has no href attribute.

I'm using jQuery to achieve very simple thing: on click start ajax request and prevent further clicks. After ajax completes, enable clicking. I don't use form or input button.

var contact= {
    send: function() {
        $.ajax({
            type: "POST",
            url: "ws/ContactService.asmx/SendEmail",
            data: '{"fromEmail":"' + $("#email").val() + '", "fromName":"' + $('#name').val() + '", "subject":"' + $('#subject').val() + '", "message":"' + $('#message').val() + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            error: function() {

                alert("Error");

            },
            success: function(msg) {
                alert(msg.d);
            },
            complete: function() {
            $("#send").text("Send");

            }
        });
    }
};
$(document).ready(function() {
    $("#send").("click", function() {
        $("#send").text("Sending...");       
        contact.send();
    });
}
);

This works fine, except that I can click on send as many times as I want and every click will produce new ajax request. How to prevent clicks on "a" element while ajax request is in progress?

A: 

Use one of these techniques, setting the link back when the ajax call returns.

cletus
+1  A: 

You could use something like this:

var contact = {
  inprogress: false,
  send: function() {
     if (contact.inprogress)
       return;

     contact.inprogress = true;
     $.ajax({
       ...
       complete: function() {
         $("#send").text("Send");
         contact.inprogress = false;
       }
     });
  }
};
sth
A: 

Or set async to false, this will freeze the page until the request is complete

David Lawson
That usually makes a pretty bad user experience, especially if the request takes a while.
icktoofay