Jorg Ancrath
Jorg Ancrath

Reputation: 1447

DOM changes inside content loaded via Ajax

I'm loading a bunch of content via jQuery Ajax, now I want to change an img src attribute inside this loaded content.

Using .click is obviously not working, to target Ajax loaded content I used .on:

$("#user_list").on('click','.block_user', function(e) {
    e.preventDefault();
    $(this).attr("src", "path_to_img_and_name.png");
});

This works just fine. The image gets replaced as it should, my problem arises when I put this change inside a NEW jquery ajax call:

$("#user_list").on('click','.block_user', function(e) {
    e.preventDefault();

    var bstatus=$(this).attr("bstatus"),
    user_id=$(this).attr("user_id");

    $.ajax({
        url: 'main/change_user_status',
        data: {
            bstatus: bstatus,
            user_id: user_id
        },
        type:'POST',
        dataType: 'json',
        success: function(output){
            $(this).attr("src", "images/"+output+"_block_user.png");
            $(this).attr("bstatus", output);
        }
    });
});

This isn't working at all.

It seems like the original content is being reloaded somehow, anyone has a clue?

Upvotes: 0

Views: 367

Answers (2)

techfoobar
techfoobar

Reputation: 66693

Use the context attribute of $.ajax() which determines the value of this inside the success callback:

$.ajax({
    url: 'main/change_user_status',
    context: this, // here 'this' refers to the #user_list that was clicked
    ...
    success: function(output) {
        // here 'this' refers to what we set as 'context'
        $(this).attr("src", "images/"+output+"_block_user.png");
        $(this).attr("bstatus", output);
    }
});

http://api.jquery.com/jQuery.ajax/ - Scroll down a little to read about context

Upvotes: 0

Paul Radich
Paul Radich

Reputation: 715

Your problem is the scope of the $(this) selector. You could use something like this

$("#user_list").on('click','.block_user', function(e) {
e.preventDefault();

var bstatus=$(this).attr("bstatus"),
user_id=$(this).attr("user_id");

var elem = $(this)

$.ajax({
    url: 'main/change_user_status',
    data: {
        bstatus: bstatus,
        user_id: user_id
    },
    type:'POST',
    dataType: 'json',
    success: function(output){
        elem.attr("src", "images/"+output+"_block_user.png");
        elem.attr("bstatus", output);
    }
});
});

Upvotes: 1

Related Questions