Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery $(this) not accessible after ajax POST?

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?

like image 627
Travis M. Avatar asked Nov 30 '22 14:11

Travis M.


2 Answers

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);
        }
    );
}
like image 147
McGarnagle Avatar answered Dec 05 '22 04:12

McGarnagle


See here: $(this) inside of AJAX success not working

You can set the context option:

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). (...)

Example:

$.ajax({
    //...
    context: this,
    success: function(json) {
        //...
    }
});

or use $.proxy:

$.ajax({
    //...
    success: $.proxy(function(json) {
         //...
    }, this)
});
like image 35
joshschreuder Avatar answered Dec 05 '22 03:12

joshschreuder