0
setTimeout( function () {
    ajaxLoadFormHeader("A", nRequest_ID, nJeppesen_Number); 
    ajaxLoadFormHeader("B", nRequest_ID, nJeppesen_Number);

    spinner.stop();

    if (document.getElementById("txt_A_Primary_Permits").checked ) {
        showRouting("A");
    }

    if (document.getElementById("txt_B_Primary_Permits").checked ) {
        showRouting("B");
    }
}, 500);

The page has two divs that hold the A and B routing information that we are using. I switch between them by hiding one and showing the other on a button click.

The ajaxLoadFormHeader() function loads data from the server into text and checkbox elements on each header form.

After the call to ajaxLoadFormheader(), I look at a checkbox element that is in each form, and depending upon which is checked, show that routing div and hide the other.

Here's the problem. Immediately following the return from the ajaxLoadFormHeader() function, when I examine the ".checked" status of the checkbox elements, they do not reflect the changes that ajaxLoadFormHeader() just set them too. At the conclusion of the ajaxLoadFormHeader() call, the values have not changed.

I suspect that the problem has something to do with how DOM values are changed by code, and that the changes are not complete and in effect until the closure of the current code block. In other words, maybe DOM changes are not visible until the completion of the setTimeout() function?

Specifics: After calling the ajaxLoadFormHeader() function, even though it does in fact set the checked status of one of the checkboxes, BOTH the (txt_A_Primary_Permits.checked) and the (txt_B_Primary_Permits.checked) return false - even though the form loads and shows the box checked.

Note: This isn't all the code. There's code for detecting if neither checkbox is checked, or handling the error condition of both being checked. I included just the relevant code for you to see the problem.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
KWallace
  • 1,570
  • 1
  • 15
  • 25

1 Answers1

1

The first A in AJAX stands for Asynchronous. If your request is indeed asynchronous, that means that your code continues to run while the request is performed in the background. That means that the spinner is stopped and the ifs are evaluated while the request is still busy, and so the status of the checkboxes is not updated yet.

The proper way to fix this, is to attach a callback or event handler to the request that is called when the request is finished. Now the exact details depend on the way you implemented ajaxLoadFormHeader, so they are hard to provide, but hopefully this information will at least help you find the right solution.

A good starting point is this question, which is answered with a 'plain vanilla' JavaScript AJAX example using the onreadystatechange event.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210