Two asynchronous AJAX requests produce identical output

Two ajax calls are being made asynchronously:

xmlhttpPostInstagram2('firsturl');
xmlhttpPostInstagram3('secondurl');

The issue is that both calls are returning the same results. Changing async to sync gives the expected different results. Any idea why this is happening with the ajax async call?

A solution without using jquery is preferred, a javascript answer would be great.

function xmlhttpPostInstagram2(strURL) {
  var originalValue = ""
  var xmlHttpReq = false;

  var self = this;
  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlXmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {

      var temp2 = document.getElementById('sidebartag');
      temp2.innerHTML = self.xmlHttpReq.responseText; // child is the fetched string from ajax call in your case
    }

  }
  self.xmlHttpReq.send();
}

and

function xmlhttpPostInstagram3(strURL) {
  var originalValue = ""
  var xmlHttpReq = false;

  var self = this;
  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {

      var temp2 = document.getElementById('sidebartag1');
      temp2.innerHTML = self.xmlHttpReq.responseText; // child is the fetched string from ajax call in your case
    }

  }
  self.xmlHttpReq.send();
}

Answer №1

Explanation without using jQuery:

In this scenario:

You are invoking the functions

xmlhttpPostInstagram2('firsturl');
and
xmlhttpPostInstagram3('secondurl');
simultaneously. When you execute the first function xmlhttpPostInstagram2, you set up the XMLHttpRequest object, but at the same time, in the second function xmlhttpPostInstagram3, you overwrite the XMLHttpRequest object because the initial request has not finished.

A solution would be to create separate instances of XMLHttpRequest in each function. Here is an example:

function xmlhttpPostInstagram2(strURL) {
    var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
    xhr.open("POST", strURL, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            var temp2 = document.getElementById("sidebartag");
            obj = JSON.parse(xhr.responseText);
            temp2.innerHTML = obj.name;
        }
    };
    xhr.send();
}

And:

function xmlhttpPostInstagram3(strURL) {
    var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
    xhr.open("POST", strURL, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            var temp2 = document.getElementById("sidebartag1");
            obj = JSON.parse(xhr.responseText);
            temp2.innerHTML = obj.name;
        }
    };
    xhr.send();
}

By utilizing these revised functions, you can effectively run them simultaneously like so:

 xmlhttpPostInstagram2("http://api.openweathermap.org/data/2.5/weather?q=London");
 xmlhttpPostInstagram3("http://api.openweathermap.org/data/2.5/weather?q=UK");

Experience Live Demo

Answer №2

It appears that the issue you are facing may be related to scope. In your code snippet, there is a line:

var self = this;

Based on the provided code, it seems that within the function's scope, this actually refers to the window object. As a result, assigning this to self makes self point to the window object. To verify this, you can add a console.log(self) statement after declaring self and check the output using your browser's developer tools.

var self = this;
console.log(self); // Outputs Window object in console.

In your subsequent code, you are executing:

self.xmlHttpReq = new ...

This means that xmlHttpReq references the same variable across both functions (i.e., window.xmlHttpReq). Consequently, when you make a call to the second function, it overwrites the value of xmlHttpReq, leading to seemingly identical results from both function calls.

To resolve this issue, you can declare xmlHttpReq as a local variable within each function's scope:

function xmlhttpPostInstagram2(){
  var xmlHttpReq;

  // For Mozilla/Safari
  if (window.XMLHttpRequest) {
    xmlHttpReq = new XMLHttpRequest();
  }
  // For IE
  else if (window.ActiveXObject) {
    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // Additional logic here...
}

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

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...

Unable to retrieve data from JSON file using Ajax request

Trying to populate an HTML table with data from an external JSON file is proving to be a challenge. Despite making an AJAX request using pure JavaScript, nothing happens when the "Test" button is clicked. Take a look at the JSON data: { "row":[ { ...

I possess an array with a specific structure that I wish to substitute the keys as demonstrated below

The data array is currently structured in this way. I have attempted various methods but have not been able to find a suitable solution. I need to send the JSON below via an AJAX request, however, I do not want the keys 0 and 1 in both child arrays. [sch ...

jQuery - harnessing the power of JavaScript events such as "dragover"

I have a JavaScript function that includes an event listener for 'dragover'. Here is the code snippet: document.getElementById("someID").addEventListener("dragover", function(){ //Add your logic here }, fa ...

Node.js: Configuring keep-alive settings in Express.js

How can I properly implement "keep alive" in an express.js web server? I came across a few examples.. Example 1: var express = require('express'); var app = express(); var server = app.listen(5001); server.on('connection', function(s ...

jQuery AJAX not properly delivering data to PHP server

For a while now, I've been struggling with a persistent issue. Despite trying numerous solutions, I still can't seem to get it to work properly. Even the simplest example like this doesn't seem to be functioning correctly in my case: jQuer ...

What are the steps to incorporating the angular/material version 7.0.1 component into my project?

My journey with Angular and Google Material Design has been successful so far. I have been building my front-end app using the official documentation from https://angular.io/tutorial and https://material.angular.io/guides. While browsing through a similar ...

Stop the replication of HTML/CSS styles during the extraction of content from a div

Is there a way to prevent the copying of CSS properties, such as font styles and sizes, when content is copied from a div? I want only the plain text to be copied to the clipboard, without any formatting applied. ...

Angular efficiently organizes data retrieved from various http requests

I have encountered a significant issue in this particular scenario. I am retrieving data from the GitHub API using the code provided below. However, due to GitHub's limitation of only allowing 30 results per page, I would like to fetch all the data fo ...

The shadow effect in three.js differs from that in Unity 3D

When I import a 3D model in .fbx format to my scene using three.js, I noticed that the shadow effect is not as sharp as when using Unity. The shadows appear too blurry. Is there a way to adjust the shadowMap setting in three.js to match the shadow quality ...

Navigate back to the previous HTML page while maintaining the existing data without causing a refresh

I have implemented an onLoad function in my HTML page to retrieve data from the server and update table rows using AngularJS ng-repeat. However, I am facing an issue where every time I navigate to another HTML page and return, the onLoad function execute ...

Responsive Bootstrap table unable to expand div upon clicking

My bootstrap responsive table has a unique functionality that allows specific divs to expand and collapse upon button click. While this feature works seamlessly in desktop view, it encounters issues on mobile devices. CSS .expandClass[aria-expanded=true] ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

Parsing error: Unforeseen token encountered. Consider adding a supplementary loader to manage the output of these loaders

Could someone please break down this syntax message?.length === 1 and show me how to convert it into standard JavaScript? https://i.stack.imgur.com/20Ui6.png I am encountering an error when trying to use a Vue.js component that I downloaded from another ...

Invalid content detected in React child element - specifically, a [object Promise] was found. This issue has been identified in next js

Why am I encountering an error when I convert my page into an async function? Everything runs smoothly when it's not an async function. The only change is that it returns a pending object, which is not the desired outcome. This is how data is being f ...

Equivalent of window.onkeypress in Typescript and NodeJS

Can someone help me figure out how to accomplish the following: document.addEventListener('keypress', (event) => { // Need this function to trigger whenever a key is pressed }); in a node.js environment using TypeScript or JavaScript? ...

how to keep form submission on hold until animation completion with jQuery

My website features a page animation where the document slides to the left when the user leaves the page. However, I am facing an issue with a form on the same page. I would like the form submission to be delayed until the animation is complete (e3ms?). D ...

JavaScript Language Conversion Templating

I'm currently revamping the frontend for Facebook's internationalization XFBML tag, which has been nonfunctional for a while. I'm almost done with the updates but I have hit a roadblock: swapping out tokenized translations without losing dat ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Using Express and Node JS to upload a text file into MongoDB

I have a simple text file that I want to upload and save in my MongoDB database. While I can successfully upload the file using basic HTML code, I am struggling with storing it. Here is what my file.html looks like: <!DOCTYPE html> <html> < ...