views:

312

answers:

3

Having issues referencing $(this) from within a the nested ajax 'success' function... I know this is a scope issue, but can't seem to find a clean way to close the dialog on a successful update. Thanks for any help.

$("#dialog_support_option_form").dialog({
        width: 400,
        height: 180,
        bgiframe: true,
        autoOpen: false,
        modal: true,
        buttons: {
            'Save Support Option': function(){
                $.ajax({
                    type: 'POST',
                    url: "support_options/create_support_option.php",
                    data: $(this).find('form').serialize(),
                    success: function(data){
                        $("#list_support_options").html(data);
                        $(this).dialog('close');
                    }
                });
            },
            'Cancel': function(){
                $(this).dialog('close');
            }
        },
        close: function(){
            $(this).find('input').val('');
        }
    });
+1  A: 

You need to have a copy of that variable, like this:

var dlg = $(this);
$.ajax({
   type: 'POST',
   url: "support_options/create_support_option.php",
   data: $(this).find('form').serialize(),
   success: function(data){
     $("#list_support_options").html(data);
     dlg.dialog('close');
   }
});

Since this is in a different context on return, you need to capture it and pass it into the closure :)

Nick Craver
eh. mo' vars, mo' problems.
Jonathan Julian
@Jonathan Julian - All these are variables inside a closure, you think `context:` doesn't set a few? :)
Nick Craver
yes, this works, but I was hoping to not use an extra variable
Dan
+1  A: 

try it with $.proxy()

success: $.proxy(function(data){
   $(this).dialog('close');
}, this);

You can 'pass' the scope from 'above' to a function with it

Kind Regards

--Andy

jAndy
+1  A: 

You should use the ajax option context: $(this), to set the scope for the callbacks to the selected element.

Jonathan Julian
boom, bang, zing. Exactly what I was looking for. Heard a rumor about this option but couldn't find it. Thanks.
Dan