Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use $(this) in ajax callback jquery

i'm doing a jQuery.post to a php file, and the file return's me a value.

the question is: why the $(this) dosent work in the callback function ? any alert passing something to show, using $(this), return's me null

$(".class").live("focusout", function(){

    jQuery.post("phpfile.php",
       {
           someValue: someValue
       },
       function(data)
       {
             // why the $(this) dosent work in the callback ?
       }                

    )

});
like image 707
Ricardo Binns Avatar asked Jun 10 '11 13:06

Ricardo Binns


1 Answers

In that case this is not the same object anymore. Save a reference before and use later:

$(".class").live("focusout", function(){
    var $this = $(this);
    jQuery.post("phpfile.php",
       {
           someValue: someValue
       },
       function(data)
       {
           // 'this' inside this scope refers to xhr object (wrapped in jQuery object)
           var x = $this;
       }                
    )
});
like image 70
BrunoLM Avatar answered Oct 11 '22 15:10

BrunoLM