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
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With