Reputation: 47605
After doing an async $.ajax call, I need to highlight the table cell that was updated.
Right now I'm using $td in the global name space, which of course is a wrong idea.
Q: How do I keep the value of $td when the jqXHR is called back? I think the answer has to do with closure, but I don't know.
var UpdateSort = function(ID,Sort){
var jqXHR = $.ajax('Remote/Ajax.cfc', {
data: {
method:'UpdateSort'
,returnformat:'json'
,paramID:ID
,paramSort:Sort
}
});
jqXHR.success(function(result){
if (result.MSG == '') {
$td.addClass('success');
} else {
$td.addClass('err');
};
});
Upvotes: 1
Views: 294
Reputation: 60414
A closure would solve your problem. Give UpdateSort
a reference to your td
and define your success function there:
var UpdateSort = function(ID,Sort, td){
var jqXHR = $.ajax('Remote/Ajax.cfc', {
data: {
method:'UpdateSort'
,returnformat:'json'
,paramID:ID
,paramSort:Sort
}
jqXHR.success(function(result){
if (result.MSG == '') {
td.addClass('success');
} else {
td.addClass('err');
};
});
});
The value of td
will be available to the function given to jqXHR.success
after UpdateSort
returns because it is in that function's lexical scope.
Upvotes: 2
Reputation:
add
var that;
to the top of your javascript file. At the end of the succes function add:
this.td = $td;
that = this;
This will store your td file in a global variable 'that' which you can use when it's called back. Take a look at this extremely useful document about variables : http://javascript.crockford.com/private.html
Upvotes: 1
Reputation: 54762
Just add it as an argument to your function.
var UpdateSort = function(ID,Sort,td){
var jqXHR = $.ajax('Remote/Ajax.cfc', {
data: {
method:'UpdateSort'
,returnformat:'json'
,paramID:ID
,paramSort:Sort
}
}).success(function(result) {
if (result.MSG == '') {
td.addClass('success');
} else {
td.addClass('err');
}
});
});
Upvotes: 2