tags:

views:

57

answers:

3

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

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.

Sarfraz
I have not included the code $(this) is referencing to. but it would be some thing like below$('#element_id').click(function(){$.ajax({...})});
askkirati
+3  A: 

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();
    });
}
nickf
This worked like charm.,.thank you
askkirati
+1  A: 

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

$.ajax({
    success: $.proxy(function(response) { $(this).parent().bla(); }, $(this));
});
Jan Jongboom
+1 I would also do it like so, but as second parameter to .proxy() parse "this" instead of "$(this)". Keeps all doors open.
jAndy