5

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 ?
       }                

    )

});
Ricardo Binns
  • 3,200
  • 6
  • 39
  • 71

2 Answers2

15

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;
       }                
    )
});
BrunoLM
  • 88,362
  • 76
  • 272
  • 427
2
$(".class").live("focusout", function(){
    var this = $(this);
    jQuery.post("phpfile.php",{
       someValue: someValue
   },function(data){
        // Now use this instead of $(this), like this.hide() or whatever.
   })
});

$(this) in your example was refering to the $.post i think.

dotty
  • 35,833
  • 64
  • 143
  • 195
  • 2
    Add a `var` declaration before your `this` call or it will leak the `this` variable into the global scope. – Femi Jun 10 '11 at 13:49