Search code examples
javascriptjqueryajaxtreeparent

How to target an element that is being clicked in a class inside ajax


I want to target some div in a class, i would use $(this), but that doesn't doesnt work since im calling that class from another function.

Sample Code.

$(document).on('click', '.Player', function(e){
    var id = $(this).find('.Song_Id').html();
    $.ajax({
    type:"POST",
    data: {data:id},
    complete: function(){
    $(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png') 
    },
    url:"php/player/get_song.php"
    }).done(function(f){
        $('#Song_info').html(f)
    });
})

From above, the following is the line i don't know how to impliment.

$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png'), 

it suppose to target class ".player", but not the entire class, only the element that was clicked.

Thanks.


Solution

  • When the ajax callback is executed, by default the execution context of the callback method is set to the ajax settings object.

    You can use the context option of $.ajax() to pass a custom execution context

    $(document).on('click', '.Player', function (e) {
        var id = $(this).find('.Song_Id').html();
        $.ajax({
            type: "POST",
            data: {
                data: id
            },
            //use context to set the execution context of the callback
            context: this,
            complete: function () {
                $(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png')
            },
            url: "php/player/get_song.php"
        }).done(function (f) {
            $('#Song_info').html(f)
        });
    })
    

    context:

    This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request