0

I have a local array in a javascript function. I am iterating a table having selections (comboboxes). For each selection I am doing an ajax call to a C# function (in the loop). In the callback method (inner function) after receiving the result I am adding it to the local array. Then after looping through the table rows I am calling another function using the array. But this array still is empty. The function with the local array is called when I change the selected item of any combobox of the table.

When I am debugging it I can see that the received item of the ajax call is added to the array in the callback function. But the array still is empty when the other function is called after looping through the table.

How I can get it to work so that the array is filled with the items when calling the function after looping through the table?

This is the function:

function doCourseCheck() {
    var errors = [];
    var chosenSubjectTypes = []; //this is the array I want to fill

    var table = document.getElementById('choiceTable');
    var selectId = 0;
    var subjectTypeReceived = function (result) {
        chosenSubjectTypes.push(result); //array is filled in the callback function (inner function)
    }


    //looping through the table
    for (let j = 0; j < table.rows.length; j++) {
        if (j === 0 || j === 3) {
            continue;
        }

        var comboBox = document.getElementById('select_' + selectId); 
        var subjectName = comboBox.options[comboBox.selectedIndex].text;
        if (subjectName !== "") {
            //in this function the ajax call is done and the result is given to the callback function
            getSubjectType(subjectName, subjectTypeReceived);
        }

        selectId++;
    }
    //here the filled array should be used but it stays empty
    checkCourseChoices(errors, chosenSubjectTypes);
    showErrors(errors);
}

This is the function where the ajax call is done:

function getSubjectType(subjectName, callback) {
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        data: { name: subjectName },
        dataType: 'json',
        url: "/Subjects/Choose?handler=SubjectType",
        cache: false,
        success: function (result) {
            callback(result);
        }
    });
}
eisem
  • 185
  • 1
  • 10
  • The array doesn't "stay empty". It gets filled, but later. Because the ajax call is asynchronous. When you call it and try to use it, it is still empty. – Jeremy Thille Nov 17 '20 at 14:35

1 Answers1

1

You cannot mix synchronous and asynchronous code. The synchronous code will always execute entirely before the asynchronous code, whatever you want to do with the array must go in the callback. In other words, you have to put this:

checkCourseChoices(errors, chosenSubjectTypes);
showErrors(errors);

Inside the subjectTypeReceived function

Guerric P
  • 30,447
  • 6
  • 48
  • 86