3

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?

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
user2557992
  • 67
  • 1
  • 2
  • 6

1 Answers1

13

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);
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67