Reputation: 6887
$(".selectedBatch").each(function(index){
var batchCode = $(this).text();
//edit batch attr start
$.ajax({
url: "../Controller/getBatchAttr.php",
type: "GET",
async: false,
data: "BM_Course_Code="+ batchCode,
success:function(resBatch){
console.log($(this).text());
//$(this).attr("data-commence-date",resBatch.BM_Commence_Date);
//$(this).attr("data-end-date",resBatch.BM_End_Date);
//$(this).attr("data-ins-days",resBatch.BM_Ins_Days);
}
});
//edit batch attr end
});
Why does console.log($(this).text());
return an empty output inside success function?
Upvotes: 0
Views: 47
Reputation: 73926
You can use the context
object here like:
$.ajax({
url: "../Controller/getBatchAttr.php",
type: "GET",
async: false,
data: "BM_Course_Code=" + batchCode,
context: this, // <--- using context as `this` here
success: function (resBatch) {
console.log($(this).text()); // Now you can use `this` here
}
});
This context
object will be made the context of all Ajax-related callbacks.
Upvotes: 0
Reputation: 6004
Inside the success function this refers to ajax object getting created when you call $.ajax. You have already created variable for the text. You can use that instead of using $(this).text()
$(".selectedBatch").each(function(index){
var batchCode = $(this).text();
//edit batch attr start
$.ajax({
url: "../Controller/getBatchAttr.php",
type: "GET",
async: false,
data: "BM_Course_Code="+ batchCode,
success:function(resBatch){
console.log(batchCode );
//$(this).attr("data-commence-date",resBatch.BM_Commence_Date);
//$(this).attr("data-end-date",resBatch.BM_End_Date);
//$(this).attr("data-ins-days",resBatch.BM_Ins_Days);
}
});
//edit batch attr end
});
Upvotes: 0
Reputation: 781917
this
is not a local variable, so it's not saved in closures. You need to set a local variable to it, and use that instead:
$(".selectedBatch").each(function(index){
var $that = $(this);
var batchCode = $that.text();
//edit batch attr start
$.ajax({
url: "../Controller/getBatchAttr.php",
type: "GET",
async: false,
data: {BM_Course_Code: batchCode},
success:function(resBatch){
console.log($that.text());
//$that.data("commence-date",resBatch.BM_Commence_Date);
//$that.data("end-date",resBatch.BM_End_Date);
//$that.data("ins-days",resBatch.BM_Ins_Days);
}
});
//edit batch attr end
});
Other changes I've made:
Pass an object as the data:
option. jQuery will ensure that it's properly URL-encoded (you forgot to call encodeURIComponent
).
Instead of .attr("data-XXX", ...)
I use .data("XXX", ...)
.
Upvotes: 3