Jump to content

jquery ajax .complete forgets what was clicked


Go to solution Solved by requinix,

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?

  • Solution

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);
      });
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.