1

I wrote small script to adding class where .done function is called, but this solution doesn't work.

$("#test").on("click", function() {

  var test = "foo bar";

  $.post({
    type: "POST",
    url: "test.php",
    data: {
      test: test
    }
  }).done(function() {
    $(this).parent().parent().addClass("success");
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><a href="#" id="test">click me</a></td>
  </tr>
</table>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
sauero
  • 259
  • 2
  • 15

2 Answers2

1

this inside the callback is not the same outside it refers to the jqXHR object of the ajax request not the element that the event handler was bound to, you should save it first outside, then use it as variable like :

$("#test").on("click", function() {
  var _this = $(this);
  var test = "foo bar";

  $.post({
    type: "POST",
    url: "test.php",
    data: {
      test: test
    }
  }).done(function() {
    _this.parent().parent().addClass("success");
  });

});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

Here is way to use this inside Ajax call. First store Node inside that variable and use that variable instead of this. I m using GET request for example , but it will work on POST request as well.

$("#test").on("click",function(){
       var that = $(this);
        var postData ={};
        $.ajax({
       type:"GET",
       url: "https://ipinfo.io/json",//your url
          data:postData,
          success: function (msg) {
                   
             },
          error:function (xhr, ajaxOptions, thrownError){
     console.log("error occured  : " +thrownError)
           } 
        }).done(function() {
    $(that).parent().parent().addClass("success");
  });;
})
.success{
background-color : #fc0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><a href="#" id="test">click me</a></td>
  </tr>
</table>
manikant gautam
  • 3,521
  • 1
  • 17
  • 27