qadenza
qadenza

Reputation: 9293

using $(this) inside ajax success function

$(".itemInto").click(function(){
var a = $(this).siblings(".itemName").html();
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "process.php",
        data: {a:a},
        success: function(data) {
            alert (data); // 20     
            $(this).siblings(".itemCount").text(data);  // doesn't work. Nothing happens.

        }
    });
});

.itemCount is a sibling of .itemInto. Why I can't place data inside it? Console is free.

Upvotes: 1

Views: 230

Answers (3)

T J
T J

Reputation: 43166

You can cache a reference to this as follows:

$(".itemInto").click(function(){
  var a = $(this).siblings(".itemName").html(),
  $this = $(this);
  $.ajax({
    type: "POST",
    dataType: "json",
    url: "process.php",
    data: {a:a},
    success: function(data) {
        alert (data); // 20     
        $this.siblings(".itemCount").text(data);  // use the cached variable instead.
    }
  });
});

Or if you must use this, you can use the native bind() method as follows:

$(".itemInto").click(function () {
var a = $(this).siblings(".itemName").html();
  $.ajax({
    type: "POST",
    dataType: "json",
    url: "process.php",
    data: {
        a: a
    },
    success: function (data) {
        alert(data); // 20     
        $(this).siblings(".itemCount").text(data);

    }.bind(this)
  });
});

Upvotes: 1

yuanzm
yuanzm

Reputation: 114

Because $(this) in callback is not $(".itemInto"),you can do like this:

$(".itemInto").click(function(){
var a = $(this).siblings(".itemName").html();
var $_this = $(this);
$.ajax({
    type: "POST",
    dataType: "json",
    url: "process.php",
    data: {a:a},
    success: function(data) {
        alert (data); // 20     
        $_this.siblings(".itemCount").text(data);  // doesn't work. Nothing happens.

    }
    });
});

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

Because the context has changed.

Try adding context: this to your AJAX parameters.

Upvotes: 4

Related Questions