user3201500
user3201500

Reputation: 1618

AJAX call with $(this) parameter in SUCCESS function

I am trying to add $this variable to success. I tried following a lot of methods, but it didn't work out as expected. Here is my code

$(document).on('click', '.add-cart-button',function(){

    $(this).find('button').find('i').attr('class', 'fa fa-spinner fa-pulse fa-fw');

    var productdetails = $(this).closest('.product-cart-details');

    var productdata = {
        'itemid' : productdetails.data('productid')
    }

    var cartbutton = $(this);
    $.ajax({
        url: productdetails.data('addtocarturl'), 
        type: 'POST',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: productdata,
        dataType: 'JSON',
        success: function(data){
            cartbutton.find('button').find('i').attr('class', 'fa fa-check');    <-------------------here is the problem. $(this) is not working
        },
        error: function(data){
            console.log(data)
        }
    });

});

I am not sure, if we can call $(this) inside another function. But I need to have figured out for this.

Thank you (in advance)!

Upvotes: 0

Views: 39

Answers (2)

Roberto Bisello
Roberto Bisello

Reputation: 1235

yes, you can, using the context option

$.ajax({
    context: this,
    url: productdetails.data('addtocarturl'), 
    type: 'POST',
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
    data: productdata,
    dataType: 'JSON',
    success: function(data){
        $(this).find('i').attr('class', 'fa fa-check');
    },
    error: function(data){
        console.log(data)
    }
});

Upvotes: 1

jlosada
jlosada

Reputation: 46

There are several ways to do it. But I use the following code:

$.ajax({
        url: productdetails.data('addtocarturl'), 
        type: 'POST',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: productdata,
        dataType: 'JSON',
        success: function(data){
            $(this).find('button').find('i').attr('class', 'fa fa-check');    <-------------------here is the problem. $(this) is not working
        }.bind(this),
        error: function(data){
            console.log(data)
        }
    });

After function bind the object then you can use $(this) inside the function. Good Luck!

Upvotes: 1

Related Questions