Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Closures and targeting 'this'

In the code example below the success callback function logs 'input#04.update' four times rather than each individual input, which makes sense seeing how closures work but how would I go about targeting each individual input using this.

<input type="text" name="" id="01" class="update">
<input type="text" name="" id="02" class="update">
<input type="text" name="" id="03" class="update">
<input type="text" name="" id="04" class="update">

function updateFields(){
 $('input.update').each(function(){
    $this = $(this);
    $.ajax({
      data: 'id=' + this.id,
      success: function(resp){
       console.log($this);
          $this.val(resp)
      }
    });
  });
}
like image 572
screenm0nkey Avatar asked Jun 11 '10 13:06

screenm0nkey


2 Answers

You forgot var

var $this = $(this);

Don't forget var. One programmer who forgot var went to bed at night and woke up to find his apartment on fire. He added var and the fire went out. Another programmer left var out completely shortly before leaving on a business trip to Europe. The airplane developed in-flight mechanical problems shortly after takeoff, causing the pilot to initiate emergency landing procedures. From his laptop the programmer quickly added var and the plane made it safely to an airport.

Don't forget var. If you put var in your code, you'll meet somebody special today. Try it. It sounds amazing but it really works!

like image 104
Pointy Avatar answered Sep 22 '22 07:09

Pointy


Pointy's correct on var usage, another alternative is to use $.proxy(), like this:

function updateFields(){
 $('input.update').each(function(){
    $.ajax({
      data: 'id=' + this.id,
      success: $.proxy(function(resp){
                 $(this).val(resp);
               }, this)
    });
  });
}

This closure creator will make this refer to the input element when you're inside the success callback, which is usually what you're after...so I'm not sure why this isn't the case by default, but in any case $.proxy() rectifies the situation.

like image 36
Nick Craver Avatar answered Sep 22 '22 07:09

Nick Craver