JQuery $(this) not accessible after ajax POST?

ajax, asp.net, javascript, jquery, scope

Solution

In general when you lose context like that, you can save a reference to the object. Like this:

function clickHandler() {
    var that = this;
    $.ajax( { url: '#',
        success: function (result) {
            $(that).text(result.d);
        }
    );
}

Problem

Let's say I have a bunch of links that share a click event: ``` <a href="#" class="do-stuff">Click me</a> <a href="#" class="do-stuff">Click me</a> <a href="#" class="do-stuff">Click me</a> <a href="#" class="do-stuff">Click me</a> ``` and in the $('.do-stuff').click function I execute a JQuery ajax POST request that updates the database with stuff and I get a successful response. After the ajax is completed, I simply want to change the value of the link text to be whatever I send back from the server... ``` $('.do-stuff').click(function () { $.ajax({ type: "POST", url: "MyWebService.asmx/DoSomething", data: '{CurrentLinkText: "'+ $(this).text() +'"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { $(this).text(result.d); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); ``` }); This invoked just fine and I verified that "result.d" is indeed the text from the server but the text is not changing. I think that the $(this) element is no longer accessible after the AJAX post? What can I do to work around this?

Original source

Related problems