tags:

views:

35

answers:

3

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?

+2  A: 

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);
    });
});
g.d.d.c
+2  A: 

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.

PetersenDidIt
+2  A: 

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});
});
Felix Kling
Thanks +1. This works, and makes more sense. But I didn't understand why I was outside the scope of this inside the get... Still don't actually. =(
Blankasaurus
@Blankasaurus: `this` is a special variable and is set to the object, a method is invoked on. You are not calling `get()` on an element but on the `jQuery` object. So inside the callback `this` cannot be set to the element, because it does not know anything about it.
Felix Kling