Jump to content

jquery ajax .complete forgets what was clicked


Recommended Posts

This little bit of code fires a database insert and gets the keyfield ID number back. Everything works, except the last part: assigning the returned number to the ID attribute of the table cell that was clicked. Looks like $.ajax knows what $(this) is, but forgets before getting to .complete.

 

How do I get the "this" variable to be recognized inside the .complete function?

 

 

$('table td').click(function() { //user clicks a table cell
      alert($(this).index()); //test case returns '9'
      $.ajax({
        url: "update.php",
        type: "POST",
        data: {
          action: 'clicked',
          clicked: $(this).index(), //the column that was clicked
          row: $(this).parent().attr('id').substr(4) //the row that was clicked (tr has an ID attribute like "row22")
        }
      })
      .complete(function(data) {
        alert($(this).index()); //test case should return '9', but returns '-1' instead.
        console.log(data.responseText); //console gets the assigned id from a database insert -- works fine.
        $(this).attr('id','ros'+data.responseText); //doesn't work. did .complete forget what $(this) is?
      });
}

 

I thought about making a hidden element, or global variable to assign $(this) to, but that seems like the long way around. Any other ideas?

As you seem to have realized, this inside the complete handler is not the same as the one inside the top click handler. Because it's all asynchronous.

 

Use a local variable.

$('table td').click(function() {
      var self = $(this);
      alert(self.index());
      $.ajax({
        url: "update.php",
        type: "POST",
        data: {
          action: 'clicked',
          clicked: self.index(),
          row: self.parent().attr('id').substr(4)
        }
      })
      .complete(function(data) {
        alert(self.index());
        console.log(data.responseText);
        self.attr('id','ros'+data.responseText);
      });
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.