views:

49

answers:

2

Why is it that the following script works clientside by removing the relievant html entity:

$(".ui-delete").click(function() {

    $.ajax({
        url: 'delete.aspx',
        type: 'POST',
        data: { strWidgetID:$(this).parents(".widget").attr("id") },
        error: function() { alert('Error'); },
        success: function() { alert('Success'); }
    });


    $(this).parents(".widget:first").remove();
});

But the following query which is "more proper", does not work by removing the html entity?

$(".ui-delete").click(function() {

    $.ajax({
        url: 'delete.aspx',
        type: 'POST',
        data: { strWidgetID:$(this).parents(".widget").attr("id") },
        error: function() { alert('Error'); },
        success: function() {
            alert('Success');
            $(this).parents(".widget:first").remove();
        }
    });

});

The first script does both clientside and serverside correctly, the second script does serverside correctly, but on clientside, it just displays an alert "success", but does not remove the html entity "widget"

Any ideas?

+2  A: 

Within the success handler, this isn't what it was in your click handler (it's the XMLHttpRequest object that $.ajax used).

Capture a reference to the this you're interested in before the $.ajax call:

$(".ui-delete").click(function() {
  var that = this;

  $.ajax({
    // etc.
    success: function() {
      $(that).parents('.widget:first').remove();
    }
  });
};
Dave Ward
That is perfect! Thanks.
oshirowanen
+1  A: 

Based on the context, $(this) refers different objects. Check out this link What is this? In the second codesample, this refers to the ajax settings object and not the 'ui-delete' element.

chedine