What steps can be taken to make sure that my Ajax request has completed before executing a new function within the window.onload event

Looking for solutions using plain vanilla JavaScript only, as I do not utilize Json or jQuery currently (I have come across several solutions on SE, but they all involve jQuery or Json).

There are two functions within a window.onload=function(){... event handler. The first function fillArray(from,to) involves an Ajax call structured like this:

function fillArray(from,to){
  request = createRequest();
  if (request == null) {
    return;
  }
  var url= "Ajax_retrieveNames.php?indexFrom=" + from + "&indexTo=" + to;
  request.open("GET", url, true);
  request.onreadystatechange = populateArray;
  request.send(null);
}

function populateArray(){
  var xmlFrag=null;
  if (request.readyState == 4) {
    if (request.status == 200) {
      xmlFrag = request.responseXML;
      for(var i=indexFrom; i<=indexTo; i++){
        fcArray[i]=new Array();
        var f=xmlFrag.getElementsByTagName("first")[i].childNodes[0].nodeValue;
        var l=xmlFrag.getElementsByTagName("last")[i].childNodes[0].nodeValue;
        fcArray[i][0]=f;
        fcArray[i][1]=l;
      }
    }else{
      return;
    }
  }else{
    return;
  }
}

The second function showNextName() handles the formatting and display of elements from the next (in this case, first) sub-array. Currently, the var arrayIndex is set to 0:

function showNextName(){
  displayQuestion() // Handles page formatting
  document.getElementById('firstName').innerHTML=fcArray[arrayIndex][0];
  document.getElementById('lastName').innerHTML=fcArray[arrayIndex][1];
  updateArrayIndex(); // Acts as a counter that increments the variable arrayIndex
}

The issue lies in the script jumping into the second function, showNextName(), before completing the Ajax call and populating the array. I have temporarily resolved this by inserting a timer between the two functions, but this feels cumbersome. Is there a more elegant way to ensure we do not prematurely enter showNextName() or exit window.onload until the Ajax call is finished and the array is populated?

Answer №1

Make sure to call showNextName within your success callback function (populateArray). It's important to keep in mind that AJAX operations are asynchronous, meaning you should only execute logic dependent on it when the readyState is 4, just like you did in the populateArray method.

function populateArray(){
  var xmlFrag=null;
  if (request.readyState == 4) {
    if (request.status == 200) {
      xmlFrag = request.responseXML;
      for(var i=indexFrom; i<=indexTo; i++){
        fcArray[i]=new Array();
        var f=xmlFrag.getElementsByTagName("first")[i].childNodes[0].nodeValue;
        var l=xmlFrag.getElementsByTagName("last")[i].childNodes[0].nodeValue;
        fcArray[i][0]=f;
        fcArray[i][1]=l;
      }
      showNextName();
    }else{
      return;
    }
  }else{
    return;
  }
}

Answer №2

To ensure efficiency, it is advisable to invoke the function showNextName within the implementation of populateArray after it completes its tasks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the tooltip of the selected item in an ng-repeat loop in AngularJS

Upon clicking an element, a function is executed which, upon successful completion, should change the tooltip of that specific element. Within an ngRepeat loop, I have multiple elements displaying the same tooltip. However, I only want to update the toolt ...

Prevent discrepancies between the outcome on the server and the client side

My website utilizes a combination of PHP and JavaScript for processing results - some server-side, some client-side. Solely relying on JavaScript can cause issues with search engine crawling, while using only PHP may not provide real-time responses accura ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...

The issue of Ajax `onreadystatechange` not functioning properly is present when using synchronous Ajax requests in versions of Firefox

Utilizing ajax and jquery for sending a synchronous http request. The use of synchronous request is necessary as I need to retrieve a value from the ajax function once the server side script has been evaluated. Although I am aware that using a synchronou ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Tips for creating brief animations

I am currently working with a moving div in JavaScript that continues to move for a period of time after the key is released. I am looking for a way to immediately stop the animation upon releasing the key. The animation is controlled by a switch statemen ...

a guide on monitoring the status of a stripe transaction through a straightforward form and javascript

Currently, I am in the process of setting up Stripe checkout for my website. I have successfully implemented the payment form, but now I need to figure out how to redirect the user to another page after a successful payment. Below is the JavaScript code th ...

Fixing the height of the body padding with JS or JQuery for a

I have a rather straightforward question that pertains to an issue I am facing while building a website using BS4. Specifically, my problem revolves around a fixed-top navbar with the class "fixed-top". The challenge stems from not knowing the actual heig ...

Is your iPhone struggling to display animation sprites correctly?

After testing on Android and iPhone, I found that the website works great on Android but lags on iPhone. I suspected that the issue might be related to image preloading, so I tried adding a simple jQuery preloader, but it didn't solve the problem. Th ...

Tips for revealing a position: absolute div that is currently hidden with display: none styling

Below is the code for a div element that I want to temporarily hide using JavaScript: <div id="mydiv" style="position: absolute; top: 60px; left:5px; right:25px; bottom:10px;"> </div> After hiding it with display:none in my ...

What is the best way to remove the left margin from a MuiTreeItem-group?

I'm working with the MUI tree component and I want to remove the left margin of the second layer of MuiTreeItem-group I attempted to use makeStyles to address this issue, but it didn't have the desired effect const useStyles = makeStyles(() => ...

What is the best way to retrieve the nearest or preceding object regardless of the document's layout using jQuery?

Here are some examples to illustrate the concept: <ul> <li id="o1" class="elem">apple</li> <li id="o2" class="elem">banana</li> <li id="o3" class="elem">orange</li> </ul> **$('#o2').exact ...

What are the steps for generating and implementing shared feature files in Cucumber?

I am currently utilizing Cucumber to define some tests for the project I am working on, but as the application grows larger, I find myself in need of a more efficient structure. project | feature_files | | app1.js | | app2.js | | app3.js ...

Unit testing promises in Angular using Jasmine

My goal is to create a unit test that demonstrates the process of combining two promises using $q.all in Angular, and then confirming that both promises are resolved simultaneously. describe("Application controller", function() { var scope; var ...

Tips for retrieving an element's outerHTML, innerHTML, and text content using JavaScript

I am new to the protractor framework and I have been struggling to find a way to access, using outerHTML/InnerHTML/getText(), the child elements in order to test if an <img> element is being displayed on a view. Specifically, I am working with an ng- ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

What is the proper way to convert nil to JSON as nil, without representing it as an empty value?

I'm facing an issue in my controller/action where some values turn out to be nil: def my_action @var1 = get_boolean_value || nil @var2 = get_int_value || nil @var3 = get_string_value || nil # there are many more values, any of them might be ...

What is the best way to transmit a modified variable from a client to a server using the fetch API?

I'm facing a challenge in sending a modified variable from the client to the server and utilizing it in main.ejs. Here's my current code: <script> document.getElementById("char2btn").addEventListener("click", change) fun ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...