i am trying to return value from ajax success function. but it is returning nothing.
JS
function calculate_total_percentage(course_log_id){
var total_percentage = 0;
$.ajax({
url:"teacher_internal_exam_management/get_exams_of_course_log/"+course_log_id,
type: "POST",
dataType: "json",
success: function (exams_of_course_log) {
for (var x = 0; x < exams_of_course_log.length; x++) {
total_percentage += parseInt(exams_of_course_log[x].marks_percentage);
}
alert(total_percentage);
return total_percentage;
}
});
}
if i call like that
alert(calculate_total_percentage(course_log_id));
then showing '61' (due to call alert(total_percentage);) but then showing 'undefined' why? It should show '61' twice? What is the problem?
The function doesn't just wait until the ajax call is complete before exiting, so you need a way to handle the return value when it does arrive...
function calculate_total_percentage(course_log_id, callback){
$.ajax({
url:"teacher_internal_exam_management/get_exams_of_course_log/"+course_log_id,
type: "POST",
dataType: "json",
success: function (exams_of_course_log) {
var total_percentage = 0;
for (var x = 0; x < exams_of_course_log.length; x++) {
total_percentage += parseInt(exams_of_course_log[x].marks_percentage);
}
callback(total_percentage);
}
});
}
You can now pass a reference to a callback function which is to be executed after the ajax call succeeds...
function calculate_total_percentage_success(total_percentage) {
alert(total_percentage);
}
Now you can call your original function like this...
calculate_total_percentage(id, calculate_total_percentage_success);
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