Organizational Research By

Surprising Reserch Topic

how to access the this inside ajax success callback function


how to access the this inside ajax success callback function  using -'jquery,ajax'

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();
            }
        });

    

asked Sep 14, 2015 by TerranceYarn
0 votes
72 views



Related Hot Questions

5 Answers

0 votes

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();
    });
}
answered Sep 14, 2015 by Ell58V
0 votes

Check out the context option - works perfectly for me:

$.ajax({
    context: this,
    type: 'post',
    url: '',
    data: 'action='+$action+'&user_id='+$user_id,
    success: function(response){
       //can access this now!
    }
});
answered Sep 14, 2015 by TandySaxtonj
0 votes

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

$.ajax({
    success: $.proxy(function(response) { $(this).parent().bla(); }, $(this));
});
answered Sep 14, 2015 by JessRoldanqn
0 votes

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.

answered Sep 14, 2015 by IFGPhi
0 votes

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.

answered Sep 14, 2015 by Jiuxnnqv

...