alagu
alagu

Reputation: 596

after jquery ajax sucess $(this) not working

I am new to js and jquery please help me with this, problem is:

$(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');

is not working.

window.onload = function() {
    $(".myclass").click(function(){
        var current_id = this.id;
            $.ajax({
                type: "POST",
                url: "/ajax.php",
                data:'current_id='+ current_id
           }).done(function(result) {
                $(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
          });
    });
}

Upvotes: 3

Views: 115

Answers (3)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

try adding context, like:

window.onload = function() {
    $(".myclass").click(function(){
        var current_id = this.id;
            $.ajax({
                type: "POST",
                context: this, //add this
                url: "/ajax.php",
                data:{current_id : current_id},
           }).done(function(result) {
                $(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
          });
    });
}

Upvotes: 1

Brad
Brad

Reputation: 163468

The context of this changes. In this case, this context is bound to the result of the Deferred done handler. In your click function store the value of this in a variable. Then, access it later.

$(".myclass").click(function(){
    var current_id = this.id;
    var $clicked = $(this);
    $.ajax({
        type: "POST",
        url: "/ajax.php",
        data:'current_id='+ current_id
    ).done(function(result) {
        $clicked.html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
    });
});

Also, I don't know why you are specifying your data the way you are, but consider just using an object, and let jQuery do the work. data: {current_id: current_id}. Otherwise, you will have to encode the values yourself.

Upvotes: 1

xdazz
xdazz

Reputation: 160893

You could use $.proxy to fix it.

$(".myclass").click(function(){

    var current_id = this.id;
        $.ajax({

            type: "POST",

            url: "/ajax.php",

            data:'current_id='+ current_id

       }).done($.proxy(function(result) {
            $(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
      }, this));  

});

Upvotes: 2

Related Questions