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

How can you retrieve the `categoryIds` key within an object that holds an array of mongodb's `ObjectId(s)` as its value?

In my Node.js code, I have the following: var getQuestionsByUserId = function (config) { var query = { _id: ObjectId(String(config.userId)) }; var projection = { categoryIds: true, _id: false }; var respondWithCategories = function (error, doc ...

Extract data from SOAP XML response sent by SOAP Client using PHP

After successfully making a SOAP call to an external webservice using PHP, I am now facing the challenge of parsing the response received from the SOAP service. When I use the following code: echo '{"reference": "'.$client->__getLastResponse ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

Setting a dynamic ID attribute for a checkbox within a jQuery DataTable

I am working with a DataTables table that is populated with JSON data provided by a Java servlet. Each row in the table contains a checkbox. I have code that can add a check to every checkbox, but I need to find a way to evaluate the value of a specific fi ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

Importing vs Referencing Videos in Next.js - What is the Best Practice for Video Integration in Next.js?

I'm looking to use a video as a background in my banner design. Typically, with images in Next.js, I would import them and then pass the import as src (for example: import img from '@images/about-us-page/img.svg'). However, when attempting ...

Adjust the stroke and fill colors of an SVG element when hovering over it

I am facing a challenge with an SVG image that I have: https://i.stack.imgur.com/r4XaX.png When hovered over or clicked, it should change to https://i.stack.imgur.com/EHRG2.png Current Icon <svg width="24" height="24" viewBox="0 0 24 24" fill="non ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Encode data in JSON format using Javascript and then decode it using PHP

In my coding journey, I decided to create an object using Javascript to pass it as an argument to a PHP script. var pattern = new Object(); pattern['@id'] = ''; pattern['@num'] = ''; pattern.cprop = new Object(); // ...

What is the best way to combine two objects in Angular?

How can I merge objects in Angular 2? Object Response 1 0:Object 1:Object 2:Object 3:Object Object Response 2 0:Object 1:Object 2:Object 3:Object MyComponent Component resultdata :any=Array; fooddrinks_data_func(Defaultparams){ return this.Ci ...

Nested objects in Gson are objects that are contained within another

In my current project, I am utilizing a library that includes a class designed to map a JSON message. Gson is being used to serialize the classes into JSON format. Within the message structure, there is a data field that is generic and can contain any type ...

Trouble arises when implementing AJAX in conjunction with PHP!

I am facing an issue with my PHP page which collects mp3 links from downloads.nl. The results are converted to XML and display correctly. However, the problem arises when trying to access this XML data using ajax. Both the files are on the same domain, b ...

What is the best way to extract a thumbnail image from a video that has been embedded

As I work on embedding a video into a webpage using lightbox, I'm looking for advice on the best design approach. Should the videos be displayed as thumbnails lined up across the page? Would it be better to use a frame from the video as an image that ...

Instructions on how to incorporate a JSON file using a node HTTP server response (without the use of express)

I recently configured my first node HTTP server and I am currently working on retrieving response data from a JSON file in my application. Everything is functioning properly when I define a JSON object directly within the server.js file. data = "{&qu ...

Using V-model in conjunction with the boostrap-vue b-table component

I am attempting to bind v-model by passing the value inside the items array. However, the binding is not functioning correctly. The main objective here is to utilize a store since all these values are utilized across multiple "wizard" components. Whe ...

"What is the best way to display a flash message upon successful completion of an AJAX request in Laravel

Is there a way to display a flash message after an ajax request redirects to a view? I'm having trouble getting the message to show up. Below is my code: Controller Code: \Session::flash('success', __('Password change successf ...

Populate an array with the present date and proceed in reverse order

In my code, there is an array that has a specific structure: var graphData = [{ data: [[1, 1300],[2, 1600], [3, 1900], [4, 2100], [5, 2500], [6, 2200], [7, 1800]} I want to replace the numbers in the first element of each sub-array with the corresponding ...

Guide on implementing JSON auto-complete for dynamically created textboxes in ASP.NET

Struggling to generate dynamic HTML textboxes on my ASPX page with autocomplete functionality? Desperately seeking a solution, I scoured various answers on StackOverflow without success. Even my script for generating new textboxes dynamically failed to del ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

The MUI Slide Transition experiences a malfunction when using multiple Slide components simultaneously

I'm having trouble getting the animations to work for each mui Slide when the button is clicked. It seems like they don't want to cooperate and work together. Oddly enough, if you disable one of the slides, the other one starts working fine, but ...