michaellunsford Posted June 6, 2014 Share Posted June 6, 2014 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? Quote Link to comment https://forums.phpfreaks.com/topic/289022-jquery-ajax-complete-forgets-what-was-clicked/ Share on other sites More sharing options...
Solution requinix Posted June 6, 2014 Solution Share Posted June 6, 2014 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); }); } Quote Link to comment https://forums.phpfreaks.com/topic/289022-jquery-ajax-complete-forgets-what-was-clicked/#findComment-1482089 Share on other sites More sharing options...
michaellunsford Posted June 6, 2014 Author Share Posted June 6, 2014 hum. thought this was local and that's why it didn't cross over. But, your solution works great. Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/289022-jquery-ajax-complete-forgets-what-was-clicked/#findComment-1482091 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.