Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();    }  }); 
like image 367
Yalamber Avatar asked Apr 15 '10 08:04

Yalamber


People also ask

How do I return data after ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

What is callback function in ajax?

Description. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.


2 Answers

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!     } }); 
like image 30
Enigma Plus Avatar answered Sep 21 '22 20:09

Enigma Plus


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();     }); } 
like image 141
nickf Avatar answered Sep 20 '22 20:09

nickf