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
$(this)
is relative to the inner-most function, 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
});
}
Well that is because context of focusout element is lost in ajax call.
You can set context
option in ajax to reference of DOM object for setting context in ajax to element context:
$("#tb2").focusout(function(){
$.ajax({
type:'POST',
url: 'validURL',
context : this,
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, $(this));
},
error: error
});
});
Alternative way you can achieve this is by referencing it in the first place.
$("#tb2").focusout(function(){
var $this = $(this);
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
validInput(data, $this);
},
error: error
});
}
The 'this' keyword within your success function, is a different 'this' that exists before your Ajax call, it's a different 'scope'.
Make a new variable for the initial 'this' so you can use it within the success callback, like so:
$("#tb1").focusout(function(){
var $this = $(this);
$.ajax({
type:'POST',
url: 'validURL',
data: {various_parameters},
contentType: 'application/json; charset=utf-8',
dataType:'json',
success: function(data){
// Here we use the $this variable, initialised before the $.ajax call.
validInput(data, $this);
},
error: error
});
}