0
$('.btn-delete').click(function(){

        var prm_delete = $.ajax({
            type: 'POST',
            url: '/gateway/delete',
            data: {id: $(this).attr('id')}
        });

        prm_delete.done(function(data){

            //how do I get the button? 
            //$(this) does not work
        });

    });

Above is my delete button code, I use a promise to send the id of the button. When the promise is done I need to get the button that was pressed so I can highlight it.

I'm having trouble with scope as done runs a function, how can I pass in the button that was pressed?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • possible duplicate of [Ajax jquery success scope](http://stackoverflow.com/questions/1570146/ajax-jquery-success-scope) – Ram Mar 03 '14 at 12:30

2 Answers2

2

Use option context of ajax:

 var prm_delete = $.ajax({
            context: this,
            type: 'POST',
            url: '/gateway/delete',
            data: {id: $(this).attr('id')}
        });

You could bind context too:

prm_delete.done(function(data){

            //how do I get the button? 
            //$(this) does not work
        }.bind(this));

Which is the same as usin jQuery $.proxy (bringing support for older browsers):

prm_delete.done($.proxy(function(data){

                //how do I get the button? 
                //$(this) does not work
            },this));
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

Try to store $(this) in another variable in order to access later:

$('.btn-delete').click(function(){
    var that = $(this);
    var prm_delete = $.ajax({
        type: 'POST',
        url: '/gateway/delete',
        data: {id: $(this).attr('id')}
    });

    prm_delete.done(function(data){
        // Now you can use that to access the `.btn-delete`
    });

});
Felix
  • 37,892
  • 8
  • 43
  • 55