Tutorial :Using $(this) within .get is undefined in jQuery



Question:

I'm using the shorthand AJAX call, $.get but when I try and reference a variable with $(this), jQuery tells me that it's undefined.

Here is the block of code:

$('.replaceWithObject').live('click', function(event) {      var cid = $(this).find('input').val();      $.get('GetVideoComment.ashx?cid=' + cid, function(data) {          $(this).html(data);      });  });  

It finds the cid just fine, as $(this) is available prior to the $.get. Inside the .get $(this) is undefined. Setting a var to $(this) prior to the get doesn't work either?

getVideoComment.ashx?cid=628 works, it returns a flash object. The issue is that $(this) is undefined inside the get.

Any idea on how to do what I want to do here? Or what I am doing wrong?


Solution:1

You need to cache your initial select so it exists when your callback fires.

$('.replaceWithObject').live('click', function(event) {      var $this = $(this);      var cid = $this.find('input').val();      $.get('GetVideoComment.ashx?cid=' + cid, function(data) {          $this.html(data);      });  });  


Solution:2

Try this:

$('.replaceWithObject').live('click', function(event) {      var that = $(this);      var cid = that.find('input').val();      $.get('GetVideoComment.ashx', {'cid': cid}, function(data) {          that.html(data);      });  });  

The problem is that this inside of the get function all is no longer .replaceWithObject If you cache the this on the click event and use that cache then it will work for you.


Solution:3

As the returned data seems to be HTML, you could also just use load():

Load data from the server and place the returned HTML into the matched element.

$('.replaceWithObject').live('click', function(event) {      var cid = $(this).find('input').val();      $(this).load('GetVideoComment.ashx?cid=' + cid);      // or $(this).load('GetVideoComment.ashx', {cid: cid});  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »