Yalamber
Yalamber

Reputation: 7580

how to access the $(this) inside ajax success callback function

It seems that i cannot access $(this) inside jquery ajax success function. please see below code.

 $.ajax({
   type: 'post',
   url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
   data: 'action='+$action+'&user_id='+$user_id,
   success: function(response){
     //cannot access $(this) here $(this).parent().remove();
   }
 });

Upvotes: 40

Views: 32202

Answers (6)

nottherealironman
nottherealironman

Reputation: 389

Now, you can simply achieve it using ES6 arrow function. You can convert the anonymous function to arrow function expression as below:

 $.ajax({
   ..,
   success: (response) => {
     // access this outside of this function scope by using `this`
   }
 });

Make sure to use transpiler such as babel to provide support for older browsers.

Upvotes: 1

mc9
mc9

Reputation: 6341

If you want this to be this in the context of your ajax call, you can also use .bind() like the following:

$.ajax({
  url: 'some_url'
  success: function(data) {
    // do something 'this'
  }.bind(this)
})

It binds the value of this inside the success callback to this outside.

Upvotes: 11

Enigma Plus
Enigma Plus

Reputation: 1548

Check out the context option - works perfectly for me:

$.ajax({
    context: this,
    type: 'post',
    url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
    data: 'action='+$action+'&user_id='+$user_id,
    success: function(response){
       //can access this now!
    }
});

Upvotes: 63

Jan Jongboom
Jan Jongboom

Reputation: 27342

Try calling $.proxy, to change the scope of this inside the function:

$.ajax({
    success: $.proxy(function(response) { $(this).parent().bla(); }, $(this));
});

Upvotes: 4

nickf
nickf

Reputation: 546273

What should $(this) be? If you have a reference to it outside that function, you can just store it into a variable.

$('#someLink').click(function() {
    var $t = $(this);
    $.ajax( ... , function() {
        $t.parent().remove();
    });
}

Upvotes: 66

Sarfraz
Sarfraz

Reputation: 382806

I can't see $(this) referencing anything but easier way would be to give the element a class or id and reference that from jquery:

Instead of:

$(this).parent().remove();

You could do:

$('#element_id').parent().remove();

Note: Here I assume that you are dealing with one element/iteration.

Upvotes: 0

Related Questions