views:

100

answers:

3
$(".delete").click(
    function()  {
        var thesender = this;
        $(thesender).text("Del...");
        $.getJSON("ajax.php", {},
            function(data) {
                if (data["result"])
                    $(thesender).remove(); // variable defined outside
                else
                    alert('Error!');
            }
        );

        return false;
    }
);

This can cause problems if user clicks on another ".delete" before the ajax callback is called?

+2  A: 

It will fire another ajax request at the same time doing the same thing. Whether that causes problems or not depends on the server side of things.

Typically you're deleting an id or key of some sort...I assume later in this code you will be, but for now it just issues another delete and call to ajax.php...what the result of this is entirely depends on that PHP page.

The callback happens for that ajax request when that ajax request finishes, each request in independent in this respect, so each callback is individually handled. thesender is inside your current closure, so it's unique as well for each request and it's respective callback.

Nick Craver
+1  A: 

Each time the click handler is called, a separate closure will be created, so each the AJAX callback will have a reference to the correct variable.

Therefore, you don't need to worry about it. (Assuming that the server can handle the requests)

SLaks
+1  A: 

It will fire another event. You could use one rather than click if you want the event to only fire once. Alternately, you can keep track as to whether an AJAX request is in progress; e.g by using data as follows:

$('.delete').click(function () {
  if ($(this).data('inProgress')) {
    // Request in progress; cancel?
    return;
  } else {
    $(this).data('inProgress', true);
  };
});

You could also achieve the same thing by using a global variable, adding classes, etc.

Matt
Thanks for the one function tip ^^
arthurprs