Is there a pre-existing function that can handle calling a JavaScript function asynchronously after the onload event has finished

I am in need of converting a javascript function that currently uses XMLHttpRequest() to perform a synchronous data fetch from the server into an asynchronous one. The function currently caches the data received to avoid multiple fetches. However, when attempting to switch to asynchronous fetching, the data is not returned in time for the callers to retrieve it. This has led to consideration of ways around the issue, such as firing functions in an onload list after the load is completed. While the synchronous method currently works fine, it is deprecated and not recommended. This has prompted the search for alternative mechanisms. One idea is to modify the XMLHttpRequest() function to track calls from other functions and handle the necessary actions once the data is received. This could involve breaking calling functions into two parts - one for requesting the data and another for handling actions post-data retrieval. Despite the potential solution, the process seems cumbersome and there may be a better way yet to be discovered. The current code snippet demonstrates the synchronous method:

    var xmlhttp;
    var dn = window.location.hostname;
    var srcURL = "http://"+dn+"/unpublished/latest/this.txt";
    if (window.XMLHttpRequest)
    {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("POST", srcURL, false);
    xmlhttp.setRequestHeader("Content-type",
     "application/x-www-form-urlencoded");
    xmlhttp.send("fname=Who&lname=Cares");
    if (xmlhttp.readyState == 4 && xmlhttp.status==200)
    {
      var siteData = xmlhttp.responseText;
      . . . 

The asynchronous version, which works in fetching the data but poses timing issues for some callers, bears resemblance to the synchronous method. Here is a snippet of the asynchronous code:

if (window.XMLHttpRequest)
{
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//callback function for the AJAX request
xmlhttp.onreadystatechange = function()
{
  if (xmlhttp.readyState == 4 && xmlhttp.status==200)
  {
    var siteData = xmlhttp.responseText;
... etc ...

Lastly, an example of the callers to the function getSiteData() is shown below:

  <script type = "text/javascript">
    function setLinkToContact(objId)
    {
      document.getElementById(objId).setAttribute('href',
       getSiteData('contact'));
    }
  </script>

There are numerous callers for the "getSiteData()" function.

Answer №1

After carefully reviewing your inquiry, I have come to understand that multiple pages necessitate data retrieval from an asynchronous function call. Each page has distinct data requirements that rely on the asynchronous callback.

If my understanding is correct, I would like to suggest an approach for you to consider.

Before initiating the async request, at the beginning of each page, create an empty global function on each page.

window.myAsyncCallback = function(){}

Each page should have a function designated to handle the async callback.

For page1:
var handleCallback1 = function(data){
    // unique handler 1
}

For page2:
var handleCallback2 = function(data){
// unique handler 2
}

Assign the handlers handleCallback1 and handleCallback2 to myAsyncCallback.

window.myAsyncCallback = handleCallback1;
window.myAsyncCallback = handleCallback2;

Then, within your onreadystatechange function, execute window.myAsyncCallback(data) with the data. Each specific implementation will activate when the data becomes available. You can now utilize the data as needed.

**********UPDATE UPDATE********

Is it possible for you to modify calls to “getSiteData(‘contact’)? If yes, you may want to consider utilizing the getSiteData.call() function and passing a reference to the DOM element requiring network data. Inside getSiteData, set the element’s dataset value. Keep track of the element in an array so you can retrieve it after the network request is completed. Then iterate through the elements list, check their value, and update as necessary since you have a reference to the DOM element.

If altering the caller function is not an option, you could explore Function prototyping. Although refactoring may require significant effort, it appears to be the best solution to prevent race conditions. If you refactor for asynchronous operations, function callbacks should suffice without delving into Promises and EventListeners; although both options are still viable, callbacks are more streamlined for your requirements.

I am intrigued to learn how you resolve this issue. Please keep me informed if feasible.

<title></title>
    <script>
        var elements = [];

        var getSiteData = function(elem, value){
            // set element data
            elem.dataset = value;

            // store
            elements.push(elem);

            // simulate async request
            setTimeout(function(){

                var xmlHttpData = {
                    "contact":"http://www.yahoo.com",
                    "contacttwo":"http://www.google.com"
                }

                linklist.forEach(function(element, index, arr){
                    // match dataset value in element to xmlHttpData. 
                    //element.dataset.value 
                })

            },3000);

        }

        function setLinkToContact(objId){
            document.getElementById(objId).setAttribute('href', 
            getSiteData.call(document.getElementById(objId),'contact'));
        }

    </script>

<body>
    <a id="link" href="">my link</a>
    <div id="linktwo">my link</a>
    <script>
        setLinkToContact('link');
        setLinkToContact('linktwo');
    </script>
</body>

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

What is the best way to query based on a nested object property in Mongoose?

const collection = [ { inner_obj: { prop: "A" } } ] Get the outer records by searching for the ones that match the value of the `prop` property within the `inner_obj` column. How can we locate the o ...

Why do two date type variables have identical content?

I'm trying to grasp why the value of d1 changes in each alert(). Any insights would be greatly appreciated. Thanks! <script> d1 = new Date("01/01/2015"); d2 = d1; alert(d1); d2.setDate(d2.getDate()+10); alert(d1); </script> ...

issues encountered with sending a multidimensional array using ajax, specifically with the index[0]

I'm struggling with sending a multidimensional array from PHP to Javascript/jQuery, encountering a peculiar issue. Upon transmitting index 0 through json_encode($array);, the desired response format is successfully received by the client: [[0,0],[1, ...

Maintain the state of the previous page in Vue to ensure continuity

Currently in the process of creating a small PWA to simulate an Android app, I have discovered Vuejs. However, I encountered an issue that has proven difficult to resolve. While scrolling through lists on the homepage for movies, TV shows, or news, clicki ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

The issue of losing session data in Laravel 4 due to multiple AJAX requests

There is an issue on my page where photos are lazy loaded via AJAX, and sometimes all session data gets lost while the photos are loading. This problem does not occur consistently every time the page is loaded. I have already checked for session timeout or ...

How can I switch to another screen from the menu located within my Parent Component?

I've been working on adding a customized navigation menu to my react-native app, but I'm currently facing the challenge of not being able to navigate to the corresponding screens of the selected menu items. I tried using this.props.navigation.nav ...

Instructions on creating a solid wall in Three.js using boxGeometry to prevent objects from passing through

I recently created a 3D maze using threejs, where I utilized BoxGeometry to construct walls that the game object cannot pass through. In my research, I discovered the importance of collision detection in ensuring the object does not go through the wall. ...

Creating a serial number in a Class without relying on a global variable is a useful technique that

I am looking for a way to assign a unique ID to each instance of a Class without relying on global variables. I have tried using a global variable and incrementing it, but I would prefer a more efficient approach. Is there a way to generate an ID within t ...

Can you explain the concept of themes in Material UI?

I am trying to wrap my head around the concept of themes and what they are meant to represent. I have gone through the documentation, but I still find it confusing. For instance, here is a snippet of code that I am referring to. I just want to understand ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

Encountering difficulties loading a Partial View using a JQuery ActionResult request in ASP.NET Core

I've been struggling with this issue for what seems like forever. Although I can initiate the ActionResult that returns PartialView("MODEL"), I'm having trouble rendering the actual View into the div within the Index cshtml page. Here's wh ...

combine multiple select options values in a single function using jQuery

My HTML code includes two select options for users to choose the origin and destination cities. I need to calculate the cost of travel between these cities. How can I compare the selected options using jQuery? </head> <body> <div> ...

Saving a MongoDB document within an array in Node.js and retrieving it

I am working on retrieving specific documents from MongoDB using Node.js and storing them in an array. const getStockComments = async (req) => { const stockname = req.params.stockName; var comments = []; var data = []; const stock = await sto ...

Merge two arrays together in Javascript by comparing and pairing corresponding elements

Dealing with two arrays here. One comes from an API and the other is fetched from Firebase. Both contain a common key, which is the TLD as illustrated below. API Array [ { "TLD" : "com", "tld_type": 1, }, "TLD" : "org", "tld_type" : 1, } ] Fi ...

vuejs default properties initialized with vue-i18n

I am trying to establish a default property from a dictionary in this way: props: { title: { type: String, default: this.$t("basic.confirm"), }, description: { type: String, } }, ... The $t function is part of the vu ...

Tips for sending data to a server in an object format using the POST method

Could someone kindly assist me? I am attempting to post user data in an object format, but it is not submitting in the desired way. Please, can someone help as I do not want it to create a new object. Here is how I would like it to be submitted: {"birthda ...

Leverage PHP variables within AJAX requests

I am currently working on implementing a specific functionality on the page "videos.php" (please note that this is all contained within a PHP echo statement): First, when a user clicks .star_' . $pvid_ID . ', it triggers the submission of a vid ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

Embed an array within a div using JavaScript

I'm looking to make a small adjustment to this code, acknowledging that it's far from perfect. Instead of simply writing the array contents into a single div, I'd like to create a new div for each number in the array and then add it to the c ...