ILikebanana
ILikebanana

Reputation: 109

Accessing data outside of ajax call in jQuery

Below is the code I am working on, my goal is to call the ajax to return some data and append that data on the button/$(this) that is clicked.

$('.click_me').click(function(){

    $.ajax({
        type: 'POST',
        url: 'ajax/get_list.php'
    }).done(function(data){
        $(this).append(data);
    });
});

Upvotes: 2

Views: 888

Answers (1)

Sachin Jain
Sachin Jain

Reputation: 21842

$.ajax returns an XHR object and it is the context which is calling the done method. Hence you need to store the context of button first before making the ajax and use that variable.

$('.click_me').click(function(){
    var $self = $(this);
    $.ajax({
        type: 'POST',
        url: 'ajax/get_list.php'
    }).done(function(data){
        $self.append(data);
    });
});

Upvotes: 2

Related Questions