Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant to be a simple array ranging from 0 to picCount, with the actual value of picCount determined by an Ajax call during page load. However, there seemed to be an issue as the picOrder array was not being properly set even though picCount was successfully retrieved. Interestingly, manually running "arrangePics();" in the console worked perfectly as it populated and shuffled the picOrder array. Unfortunately, simply placing calls to both functions inside "" or enclosing them within the "doStuff()" function did not yield the desired results.

Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
while (s.length) this.push(s.pop());
return this;
}

var picOrder = new Array();
var picCount;

function getPicCount() {
//  picCount = array(10);
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      } else {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            picCount = xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","/example.com/images.php?count=hello",true);
    xmlhttp.send();
    //picCount.shuffle;

}

function arrangePics() {
    for(var i = 0;i<picCount;i++) {
    picOrder[i] = i;
    }
    picOrder.shuffle();
    //alert(picOrder);
}

HTML

<body onLoad="getPicCount();arrangePics();">

or

<body onLoad="doStuff();">

Answer №1

To ensure proper functionality, be sure to execute the arrangePics() function only after the asynchronous AJAX call has successfully returned. This means you should include it within the

if (xmlhttp.readyState==4 && xmlhttp.status==200) {}
block to guarantee that all data has been fully received before arranging the pictures.

The issue currently arises from JavaScript calling getPicCount();arrangePics(); sequentially. Since the first method triggers the AJAX request and returns immediately, the second method attempts to arrange zero pictures. By manually running arrangePics() in the console, it introduces a delay that allows the AJAX call to finish, setting the expected picCount.

To resolve this issue, update the callback function to:

if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    picCount = xmlhttp.responseText;

    for(var i = 0;i<picCount;i++) {
        picOrder[i] = i;
    }
    picOrder.shuffle();
}

This adjustment will properly shuffle the pictures once the count has been retrieved from the server.

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

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...

Seeking help with a Javascript regex inquiry

I am currently utilizing JavaScript regex for the following task: I have gathered the HTML content from a page and stored it within a string. Now, I aim to identify all URLs present on this page. For instance, if the document includes-- <script src = ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

Display or conceal a vue-strap spinner within a parent or child component

To ensure the spinner appears before a component mounts and hides after an AJAX request is complete, I am utilizing the yuche/vue-strap spinner. This spinner is positioned in the parent days.vue template immediately preceding the cycles.vue template. The ...

Run JavaScript code that is retrieved through an ajax request in Ruby on Rails

When I use Rails to render a javascript view, the code looks like this: $("##{@organization.id}-organization-introtext").hide(); $("##{@organization.id}-organization-full").append("#{escape_javascript(render @organization)}").hide().fadeIn('slow&apos ...

ESLint is reminding you that the `parserOptions.project` setting must be configured to reference the tsconfig.json files specific to your

Within my NX Workspace, I am developing a NestJS-Angular project. Upon running nx lint, an error is triggered with the following message: Error: A lint rule requiring the TypeScript type-checker to be fully available has been attempted, but `parserOptions. ...

A mistake occured: Unable to modify the stack property of [object Object], as it only has a getter method

Encountering an error when attempting to use a service in my component and declaring it in the constructor - TypeError: Cannot set property stack of [object Object] which has only a getter This is the code snippet: import { Component } from '@angula ...

Is it possible to access an external website by clicking on a link within a DIV element?

I have a basic website set up like this sample.php <html> <head></head> <body> <a id="myLink" href="http://sample.com">Click!</a> </body> </html> I displayed this website within a DIV-Container on a ...

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

Node.js and TestCafe encountered a critical error: Inefficient mark-compacts were performed near the heap limit, resulting in an allocation failure. The JavaScript heap ran

While executing my test scripts in Node v14.6.0, I encountered the following problem. Here are some of the options I've tried: I attempted to increase the Node Heap Size but unfortunately had no success: export NODE_OPTIONS=--max_old_space_size=4096 ...

Troubleshooting: Issues with Custom Image Loader in Next.js Export

I'm encountering a problem while attempting to build and export my Next.JS project. The issue lies with Image Optimization error during the export process. To address this, I have developed a custom loader by creating a file /services/imageLoader.js ...

Tips for sending context in the success callback function of a jQuery AJAX request

const Box = function(){ this.parameters = {name:"rajakvk", year:2010}; Box.prototype.callJsp = function() { $.ajax({ type: "post", url: "some url", success: this.executeSuccess.bind(this), err ...

Having trouble loading select2 using PHP/Ajax/JSON even though I can see the data in the inspector

I encountered a puzzling issue after deploying my web application from a Windows (XAMPP environment) to a Linux Server. Despite everything working perfectly on Windows, I am now facing a frustrating problem that has left me stumped. I have scoured through ...

Focus on input using jQuery (fixed focus)

How can I ensure that my input always has value and the focus remains fixed on it until values are typed, preventing the cursor from escaping the input field? While I know the existence of the focus() function, how can I effectively utilize it as an event ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

Tips for making Ajax crawlable with jQuery

I want to create a crawlable AJAX feature using jQuery. I previously used jQuery Ajax on my website for searching, but nothing was indexed. Here is my new approach: <a href="www.example.com/page1" id="linkA">page 1</a> I display the results ...

Ways to generate data following the integration of Firebase Firestore in Vue.JS

How can I display the orders data retrieved from Firebase in my browser console? See the image link below for reference. This is the code snippet for fetching data from Firebase and displaying it in the console: orders(){ const db = firebase.firestor ...

Is it possible for me to include detailed information to a particular attribute of an object?

Although the code below is incorrect, it reflects my intention. Can this be achieved? I am looking to update the original array so that all orderno values are formatted as 000.0.000.00000.0. let cars= [ {orderno: "5766302385925", make: "Alfa", dealersh ...