Confusion with Callbacks Due to Asynchronous Ajax Requests

Essentially, I have a standard ajax function set up like this:

    function ajax_request(rest_req, url, success_callback, fail_callback) {

    var xhttp = new XMLHttpRequest;

    xhttp.onreadystatechange = function () {
        if (this.readyState == 4) {
            if (this.status == 200) {
                success_callback(this);
            }
            else {
                fail_callback(this);
            }
        }
    };

    xhttp.open(rest_req, url, true);
    xhttp.send();
    }

When using the ajax function in this manner:

(function() {
 function setup() {
   ajax_request("GET", "url1", function(xhttp) {
        response = JSON.parse(xhttp.responseText);
        if (response["error"] != 100)
            document.getElementById('url1-reading').innerHTML = '---';
        else
            document.getElementById('url1-reading').innerText = response["response"];
    },
        function() {} 
    );

    ajax_request("GET", "url2" , function(xhttp) {
        response = JSON.parse(xhttp.responseText);
        if (response["error"] != 100)
            document.getElementById('url2-reading').innerHTML = '---';
        else
            document.getElementById('url2-reading').innerText = response["response"];
    }, 
        function() {}
    );

    console.log('Refresh');

  }

   setInterval(setup, 1000);
  })();

This code is not behaving as expected. Sometimes, the results intended for url1's success_callback end up inside url2's success_callback.

In other words, the response variable within the ajax_call for url1 is mistakenly being used as the response variable for url2. It seems that the ajax_call does not correctly associate the success_callback with its designated URL despite it being passed as a parameter.

Coming from a C++ background, this concept is challenging to grasp. How can I ensure the correct assignment of success_callbacks to their respective URLs? Please let me know if there are any unclear points that need clarification.

Answer №1

If you declare it like this, response will now be a global variable. Consider modifying response = to let response =

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

Converting strings into time formats in MongoDB

My string appears as follows: schedule_time = { start_time : "13:00", end_time : "14:10" } Now I need to convert it into time in MongoDB. I attempted using dateFromString but encountered some issues. The aggregation query: db.getCollection('appoi ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...

Sharing data between ejs and javascript files

When using Express, I have encountered an issue with passing a variable to an EJS file called "index.ejs". res.render("index",{passedUser:req.user.alias}) Although I am able to successfully print it using <%=passedUser%> in the EJS file, I require ...

Comparing Node.js and Node on Ubuntu 12.04

After following the instructions on this website, I successfully installed nodejs on my ubuntu system. However, when I type node --version in the terminal, I get an error message saying: -bash: /usr/sbin/node: No such file or directory Oddly enough, ...

Failure of Chrome to automatically mark checkboxes as checked upon page loading

When a user clicks on checkboxes on my page, an ajax call is made to the server with form data from the checkboxes to filter the list. However, all settings are lost when the user navigates to another page. To retain checkbox form data, I want to store it ...

What is the process for returning data to the Front end once the functions activated by a webhook have been executed?

My current project involves utilizing the Plaid API to collect transaction data from users. Plaid sends updates to our webhook endpoint to notify us when the data is ready for retrieval. Once we receive the code from Plaid indicating that the transaction d ...

I am facing an issue with resolving services in my AngularJS controller

Having trouble resolving the service data in AngularJS controller. var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) { var promise = dataFactory.getResult().then(function(data ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

The field 'shouldComponentUpdate' cannot be reassigned to itself

I encountered a TypeScript error while using shouldComponentUpdate: The error message states: "Property 'shouldComponentUpdate' in type 'Hello' is not assignable to the same property in base type Component<IProps, any, any>." ...

Guide for skipping the presentation of data in column1, when column2 contains multiple lines of content

How can I avoid showing redundant data for ItemA when ItemB has multiple lines to display: ItemA = [Color Fruit, Nuts] ItemB = [[green], [orange, apple, grapes], [cashew, almond]] if (this.point.customTT === 'Item') { ...

Adding a class to a Vue component using the $refs property

I am facing an issue where I need to add dynamic class names to various Vue components based on their reference names listed in a configuration file. Manually adding classes to each component is not feasible due to the large number of components. To addre ...

The selector is not able to be located by the jQuery click function

let obj = new object(); obj.loadInterface(); $("button").click(function() { obj.doSomething(); }); The issue arises because obj.loadInterface() loads the button into the DOM at the end of a $.post() function since server data is required to set some ...

Modification of window size using jQuery animations

Currently, I am working on creating a sidebar that slides in from the left side of the screen. To achieve this effect, I have set the menu element to float left with a width of 40% and a margin-left of -40%. However, when I try to reveal the sidebar by sw ...

Exploring React: Opening a new page without rendering the SideBar component

I currently have an application with a sidebar that navigates to three different pages, all of which include a navigation bar and the sidebar. However, for the next page I want to exclude the sidebar but still include the navigation bar. How can I configur ...

tips for sending URL parameters to the server using AJAX

It may seem like a simple task, but I've struggled to find a practical solution. Let's consider an URL with a GET value of: /?userid=1 How can I pass the dynamic value of 1 using AJAX? The userid varies based on the link that is clicked, so i ...

Passing and removing array parameters in HTTP requests using Angular

I have an Array of statuses objects. Each status has a name and a boolean set to false by default. These represent checkboxes in a form with filters - when a checkbox is checked, the boolean value is set to true: const filters.statuses = [ { name ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

Access the value of a JavaScript global variable using Selenium in Python

I need to access a value from a global variable in JavaScript: clearInterval(countdownTimerTHx); var saniye_thx = 298 // <--- Variable here function secondPassedTHx() { https://i.sstatic.net/odIbh.png My goal is to retrieve the value " ...

Save the output of a function in node.js

I have created a function that utilizes the nodejs module recursive-readdir to read all files within a folder recursively. The function is functioning correctly, but I am facing an issue with exporting the 'routes' array using 'module.export ...

GM Unable to Establish Cross-Domain Ajax Connection

Attempting to populate a form on a client's website with data from our database using a Greasemonkey script, but struggling with the same origin policy. I have tried using GM_xmlhttpRequest and even specified @grant GM_xmlhttpRequest but without succ ...