JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm going wrong... but I don't want to make the calls synchronous for obvious reasons.

Here is the JavaScript code I'm using to create a new XMLHttpRequest:

function createRequest(){
  if(window.XMLHttpRequest)
    return new XMLHttpRequest;
  else 
    return new ActiveXObject("Microsoft.XMLHTTP");
}

This is my send request function (to send the requests):

function sendRequest( url, callback){
  request = createRequest();

  if(typeof callback === 'function'){
    request.onreadystatechange = callback();
  }

  request.open("GET", url, true);
  request.send();
}

And finally, my callback function:

function handleData(){
  return function(){
    if (request.readyState == 4 && request.status == 200) {
        serverResponse = JSON.parse(request.responseText);

        switch(Object.keys(serverResponse)[0]){
            case "a": function1(serverResponse.a,"a"); break;
            case "b": function2(serverResponse.b,"b"); break;
        }
    }
}

I am making my calls like this:

window.onload = function () {
  sendRequest('url' , handleData);
  sendRequest('url2', handleData);
}

Please note that this is a simplified version of my code. In the switch statement, I am calling function1 and function2 to handle the JSON response from the server. The problem occurs when I try to make two consecutive calls - only the second one succeeds. It seems like the second call is overwriting the first one.

I attempted to create separate functions for handling the data, so I had handleData1() and handleData2() instead of a single handleData(). But again, only the second call was successful. When I added console.log(request) in both functions, I only saw JSON data for the second function being processed. Sometimes the second function was called multiple times, up to 4.

For clarification, handleData2 does not depend on data from handleData1.

If you have any further questions, please feel free to ask. Thank you!

Answer №1

const httpRequest = createRequest();

This code snippet is creating a global variable, which means that every time the function is called, it will override the variable causing unexpected behavior.

To avoid this issue, you can create a local variable and pass its value to the callback function like this:

const request = createRequest();

if(typeof callback === 'function'){
  request.onreadystatechange = callback(request);
}

// ...

function handleResponseData(request) {
    // ...
}

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

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...

The premature reveal of the back side in the Kendo UI flip effect on Internet Explorer

Currently, I am in the process of creating a BI dashboard for a business application using JavaScript Kendo UI version v2014.1.416. Unfortunately, I have encountered an issue with certain visuals while testing on IE11. I must mention that due to practical ...

Using jQuery each with an asynchronous ajax call may lead to the code executing before the ajax call is completed

In my jQuery script, I utilize an each loop to iterate through values entered in a repeated form field on a Symfony 3 CRM platform. The script includes a $.post function that sends the inputted value to a function responsible for checking database duplicat ...

Using JavaScript Functions to Resize Buttons and Change function on Click

I have a button in my code that triggers CSS changes by adding and removing classes. The JavaScript for this function works as intended - clicking once adds the class, clicking again removes it, and so on. However, I also implemented a feature to remove t ...

How can I select the specific element within a class when a particular checkbox is selected?

Having a dynamically generated list of elements, each structured like this: <div class="under-item-description"> <span class="under-compare-price">100</span><span class="under-price">50</span> <span class="under-compar ...

Unable to translate the Json String into Java objects

I'm facing difficulties in converting the Json String to a Java Object After validating the Json format, it appears to be correct. @JsonIgnoreProperties(ignoreUnknown = true) public class DevPol { private String id; private Header header; ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

Steps for showcasing the data entered in the input box

I am looking to enhance my skills in working with Angular and JavaScript. I would greatly appreciate any feedback on the issue I am facing here. My goal is for the text box input to display: "hello {name} , would you like to play a game? However, curr ...

Populate a table dynamically in JavaScript using a variable

I have a table with IDs such as r0c1 = row 0 column 1. I attempted to populate it using the following script, but it doesn't seem to be functioning correctly: var data = new Array(); data[0] = new Array("999", "220", "440", "840", "1 300", "1 580", " ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...

performing an AJAX call utilizing both a file and post data

I'm reaching out for help because I'm having trouble sending an ajax request with a data file and two posts included Here is the code snippet: $('#image--1').change(function (e) { e.preventDefault(); var img = new FormData(); ...

Is there a way to run only one instance of puppeteer.launch() and simply forward pages to it in Node.js?

I have a concern regarding the code snippet below. It appears to be launching the browser on every request, potentially causing server issues on Heroku. I would like to modify it so that puppeteer is launched as a Singleton instance, where it only needs ...

Enhancing a variable's value while simultaneously boosting its rate of increase through Javascript

Looking to adjust the timing on a number increase function using setInterval(Function, time). Initially set the variable for time as time = 1000, but now looking to dynamically change it by implementing a function triggered by a button click: function cha ...

Incorrect positioning on canvas

Is there a way to adjust text alignment within a canvas? Currently, my text is centered. However, when I change the text size, the alignment gets thrown off. Here is the code snippet: <canvas id="puzzle" width="480" height="480"></canvas> ...

Chrome is experiencing a delay in closing the Select Option dropdown menu

On my webpage, I have two select option buttons placed on different tabs. Whenever one button is changed, I want to update the value of the other button and assign it to a specific element like a span in the example code provided. While everything works sm ...

The tags are showing unexpected strings after the v-for directive

Currently, I am in the process of designing a new web page using Vue on Nuxt to replace the existing one (using VScode). However, I have encountered an issue while utilizing v-for to generate lists. Within the tag, there is an unknown string(attribute) tha ...

Exploring the differences between server-side rendering and client-side rendering in Express using Pug

I find myself in a state of confusion when it comes to distinguishing between what is considered client-side and server-side. Currently, as I develop a website using Pug for my HTML pages without any external files being loaded into the client's brows ...

Retrieving a JSON object based on its name

Here is the structure of a JSON object I am working with: [ { "filters": [ { "name": "category", "list": [ { "category-abc": { "title": "abc", "number": "2" ...

Pinia throws a useStore is not callable error

I have been trying to resolve the issue with (0 , pinia__WEBPACK_IMPORTED_MODULE_1__.useStore) is not a function but unfortunately, I haven't been able to find a solution. Can anyone point out what mistake I am making? Here is my store.js code: im ...