Ajax jquery success scope Ajax jquery success scope ajax ajax

Ajax jquery success scope


You should use the context setting as in http://api.jquery.com/jQuery.ajax/

function doop(){    var old = $(this).siblings('.old').html();    var newValue = $(this).siblings('.new').val();    $.ajax({        url: 'doop.php',        type: 'POST',        context: this,        data: 'before=' + old + '&after=' + newValue,        success: function(resp) {            if(resp == 1) {                $(this).siblings('.old').html(newValue);            }        }    });    return false;}

"this" will be transfer to the success scope and will act as expected.


First of all new is a reserved word. You need to rename that variable.

To answer your question, Yes, you need to save this in a variable outside the success callback, and reference it inside your success handler code:

var that = this;$.ajax({    // ...    success: function(resp) {        if(resp == 1) {            $(that).siblings('.old').html($new);        }    }})

This is called a closure.


this is bound to the object to which the executing function was applied. That could be some AJAX response object, or the global object (window), or something else (depending on the implementation of $.ajax.

Do I need to capture $(this) into a variable before entering the $.ajax call, and then pass it as a parameter to the $.ajax call? or do I need to pass it to the anonymous success function? If that's going to solve the problem, where do I pass it to the $.ajax?

You do indeed need a way to capture the value of this before defining the success function. Creating a closure is the way to do this. You need to define a separate variable (e.g. self):

function doop() {    var old = $(this).siblings('.old').html();    var new = $(this).siblings('.new').val();    var self = this;    $.ajax({        url: 'doop.php',        type: 'POST',        data: 'before=' + old + '&after=' + new,        success: function(resp) {            if(resp == 1) {                $(self).siblings('.old').html(new);            }        }    });    return false;}

The success function will retain the value of self when invoked, and should behave as you expected.