0

My question is the flow of this code. I am assuming execution flows from top to bottom in JS. When I use F12 and step through the execution it seems to be hitting all the "VAR" lines then jumps over the AJAX call and executes the last line where I concatenate the two strings, then the execution goes back to the AJAX call. While debugging I see the ajax call is getting the correct value from SQL and brings it back but it seems to execute after I have already concatenated the 2 strings and wrote them back to "SalesOrderGeneratedNumberID" field. This is my first web app so I am still learning JS. any ideas why the code execution is jumping over the AJAX call then coming back to it?

// Generate Sales order number located at top of the page
function GenerateSalesOrderNumber() {
    var strDate = new Date();
    var shortYear = strDate.getFullYear();
    var twoDigitYear = shortYear.toString().substr(-2);

    var elem = document.getElementById("HubCountryID");
    var strCountryHubVal = elem.options[elem.selectedIndex].text;

    var strSalesRegionVal = document.getElementById("SalesRegionID").value;

    var strBusinessUnitVal = document.getElementById("SelectBusinessUnitId").value;

    var strSalesOrderNumberPrefix = twoDigitYear + strCountryHubVal + strSalesRegionVal + strBusinessUnitVal;
    var strSalesOrderNumberSuffix = "";
    $.ajax
        ({
            type: "GET",
            url: "/NewOrder/?handler=SalesOrderNumber",
            data: {},
            contentType: "JSON",
            success: function (response) {
                console.log(response),
                    strSalesOrderNumberSuffix = response.sonRunningNumber;
            },
            error: function (data) {
                alert(data);
            }
        });

    document.getElementById("SalesOrderGeneratedNumberID").value = strSalesOrderNumberPrefix + strSalesOrderNumberSuffix;
}
  • 1
    `strSalesOrderNumberSuffix = response.sonRunningNumber` this will likely not run before `.value = strSalesOrderNumberPrefix ...` – evolutionxbox Jul 28 '21 at 21:35
  • 1
    Does this answer your question? [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – evolutionxbox Jul 28 '21 at 21:35
  • Welcome to the world of asynchronous programming. The `$.ajax()` "success" callback will not be invoked until the HTTP request completes, but the `$.ajax()` call itself will return essentially immediately. – Pointy Jul 28 '21 at 21:36
  • move `document.getElementById("SalesOrderGeneratedNumberID").value` assignment into `success: function (response)`. `success` function is executed after the AJAX response is finished. It will set value for `strSalesOrderNumberSuffix` and `SalesOrderGeneratedNumberID` value should also be updated at that time. – Vitalii Jul 28 '21 at 21:41

0 Answers0