SeeDosRun SeeDosRun - 6 months ago 19
jQuery Question

How to pass $(this) in success callback of $.ajax

I have seen a few different examples of accessing $(this) is the success callback of ajax but none give me the answer I want - they all access $(this) within the ajax function, I want to pass $(this) to a separate function.

So if there are 2 textboxes that need to be validated

$("#tb1").focusout(function(){
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, $(this));
},
error: error
});
}

$("#tb2").focusout(function(){
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, $(this));
},
error: error
});
}

function validInput(response, obj){
console.log(response.d);
console.log(obj.val());
};


When I run the code I get the correct value for response.d but an error : jquery-1.11.1.min.js:4 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined for obj.val().

Am I doing something wrong?

Thanks for any help.
See:Dos/Run

Answer

$(this) is relative, and in this case you'll need to assign $(this) to a variable before the ajax query, and use that variable in the success instead.

$("#tb1").focusout(function(){
    var elem = $(this);
    $.ajax({
        type:'POST',
        url: 'validURL',
        data: {various_parameters},
        contentType: 'application/json; charset=utf-8',
        dataType:'json',
        success: function(data){
            validInput(data, elem);
        },
        error: error
    });
}
Comments