Search code examples
javascriptajaxscopeanonymous-methods

anonymous function variable scope [js, ajax]


$(".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?


Solution

  • 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.