The Ajax code is not functioning as expected. The first one is not being displayed in the two connected XHR functions

fiddle : http://fiddle.jshell.net/xvwz2bt4/

Using the ajax code below (pure js) :

var xhr;
xhr = new XMLHttpRequest();
function xhrDocOpen(doc,placeID){
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4 && xhr.status==200){
            document.getElementById(placeID).innerHTML=xhr.responseText;
        }
    }
    xhr.open('GET',doc,true);
    xhr.send();
}
xhrDocOpen('a.txt','apple');
xhrDocOpen('b.txt','banana');

Initially, I believed this code to be correct.

However, upon further testing, it became apparent that it was not functioning as intended.

In the 'xhrDocOpen' function above, the first one doesn't display a.txt... While the second one displays b.txt correctly.

The reason behind this issue is currently unknown...

Can anyone identify the problem?

Answer №1

After testing this on my personal computer, I discovered that using the same XMLHttpRequest for multiple calls to xhrDocOpen in rapid succession can lead to issues. Specifically, the onreadystatechange function ends up being assigned to the last one set during the previous call to xhrDocOpen, preventing the proper setting of a.text. To resolve this, relocating the var xhr = new XMLHttpRequest(); statement within the xhrDocOpen function should solve the problem.

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

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

Utilizing Vue and Websockets for seamless communication: Managing the exchange of messages between users

In an attempt to create a messaging system that shows alerts of messages to different users, I have implemented Vue Socket Io from https://www.npmjs.com/package/vue-socket.io. However, the issue lies in the fact that the alerts are not being triggered as e ...

Using Three.js to spin a mesh in the direction of a sphere

As a newcomer to Three js, I've been grappling with a challenge lately. My 3D model is currently facing a specific direction, surrounded by a sphere. Before I move the mesh, I want to animate its rotation so that it aligns with the specified sphere. ...

Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not bein ...

Tips for ensuring successful testing of OAuth flow using the Login Kit feature on the Snapchat API

My current focus is on learning about the Snapchat API and I've started by delving into their Login Kit feature through a web tutorial. However, I've hit a roadblock. Whenever I try to proceed past the Snapchat login site, all I see is a message ...

Making an Ajax call using slash-separated parameters

Handling APIs that require slash-separated parameters in the URL can be quite tricky. Take for example: http://example.com/api/get_nearest_places/:en_type_id/:longitude/:latitude One way to build this URL is by concatenating strings like so: var longitu ...

Struggles with loading order in Knockout.JS

I've encountered an issue with loading my scripts properly for a page utilizing a knockout.js form. Upon page load, my viewmodel js file isn't immediately loaded, resulting in errors that cause the validation messages to flash and hidden divs to ...

Utilizing jQuery to Convert JSON Array Data into a Table

I am having trouble populating a table with data from a JSON array. The data is showing up in the console but I can't seem to get it into the table. Data is visible in the console screenshot below https://i.sstatic.net/C7L7d.jpg Here's what I& ...

Incorporate an image into your webpage with the Fetch API by specifying the image link - JavaScript

I've been attempting to retrieve an image using the imageLink provided by the backend server. fetchImage(imageLink) { let result; const url = `https://company.com/internal/document/download?ID=${imageLink}`; const proxyurl = 'https:/ ...

Filtering a 2-dimensional array based on a specific string match

I have an array with various objects and I am trying to find all objects that have the string "en-GB". However, I am encountering an issue with my current approach that gives me the error message "Cannot use 'in' operator to search for 'en&a ...

When inputting forms into the database, identifiers are used instead of names. Despite this, the user interface functions without any issues

In this demonstration, I am building a dynamic conditional drop-down list using Java script and Ajax. PHP: Add Data <html> <head> <title>Add Data</title> </head> <body> <?php //including the database connection ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

Occasionally, wmuslider fails to load properly

I am currently developing a website for a dance studio and have implemented the wmuslider to create a slider on the homepage. However, I am encountering an issue where the slider does not consistently load. This seems to be a problem across different brows ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Is there a way to invoke a function from a component that is neither a direct child nor parent component?

Module X let searchQuery = .... retrieveData(searchQuery); Module Y //implementing the use of Module X's parameter ...

Changing a DOM structure into pure HTML using JavaScript

Looking to convert some HTML into a PDF file using a service that requires form-data as the payload. Is there a way to extract HTML from the DOM and save it as a file for use in the payload? <p>some other HTML</p> <div id="content"> ...

Tips for keeping an image stationary when hovering over it

I'm in need of some assistance. Despite my best efforts, I have been unable to achieve the desired outcome. I am looking to create a scenario where an image remains in place even when the mouse hovers over it. Essentially, I want the image to stay vis ...

The functionality of displaying a loading image when the Upload button is clicked has encountered a glitch and

I am looking to add a feature that displays a loader when a user uploads a file by clicking on a button. The loader should be visible while the data is being processed in the background. To achieve this, I have included a div as shown below: <div id=" ...