Utilizing AJAX and Javascript to assign text file contents to a JavaScript variable

After attempting to extract a list of words from a txt file and store it in a JavaScript variable for future use, I've encountered an issue. The problem lies in my inability to transfer the variable outside of the onreadystatechange function. Could there be a simple solution that has eluded me?

Original Source:

var xmlhttp;
var list = new Array();
var word;

if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        list = xmlhttp.responseText.split("\n");
        document.getElementById("testfield").innerHTML = list[0]; //This works
        word = list[0];
    }
}

xmlhttp.open("GET","wordlist.txt",true);
xmlhttp.send();

document.getElementById("testfield").innerHTML = word; //This doesn't work

Answer №1

The issue lies in the execution order of this code snippet

document.getElementById("testfield").innerHTML = word; //This doesn't work

This code is running before the xhr callback function. Consequently, the value of word is undefined

The xmlhttp.send(); method initiates the ajax request and returns immediately. Subsequently, your code attempts to update the testfield element with the undefined word value.

document.getElementById("testfield").innerHTML = word;

When the ajax request eventually completes and the callback function is executed, the word variable is assigned a value. However, at that point, it is too late for the updated value to be relevant.

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

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

The ID Token could not be verified due to an invalid jwt.split function

I'm currently working on validating a Google ID Token on my Node.js server. Unfortunately, I've encountered the following error: The ID Token cannot be verified: jwt.split is not a function For reference, here is the link to the code that I am ...

What is the reason behind the jQuery JSON parser requiring double escaping for backslashes?

I'm struggling to comprehend a strange aspect of the JSON data format. Here's the issue: I have a string with a Windows directory path, where backslashes are escaped. However, the jQuery JSON parser seems to require double escaping for some reas ...

Arranging a collection of objects (Displaying information in a random sequence)

Here is a summary of the data returned in a shortened version: var array = [{ "response": { "itineraries":[ { "price": { "totalPricePerPassenger":"104" ...

Set a generic function type to a variable

Currently, I am facing an issue where I have a declared function type with generics that I want to assign to a named arrow function. Below is an example of the code: import { AutocompleteProps } from '@material-ui/lab/Autocomplete'; const itemTo ...

Having trouble debugging JavaScript as a beginner? Unable to pull the cookie value and use it as a variable? Let's

Hello everyone, I'm new to coding and have been working on a project. However, I am facing some errors and need help debugging. I have a cookie named "country" with a value of "AZ" that I want to retrieve using JavaScript and use it in my Google Maps ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

The return value of a jQuery post request is consistently false

When I click on a tag, my code returns true but the data variable is false. Can you explain why this is happening? $('#AddProvince').click(function () { var url = '@Url.Action("SetProvinceList")'; var id = $('#Province&apo ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

How do I avoid using an if statement in jQuery to eliminate errors caused by "undefined" values?

Whenever I incorporate third-party plugins, my usual practice is to initiate them in the main application.js file. For example: $('.scroll').jScrollPane(); However, a challenge arises when a page loads without the presence of the scroll class, ...

Redirect the URL in react-snap to a new URL with a forward slash at the end

I recently implemented react-snap to generate static HTML for my website. However, I encountered some SEO issues after implementing react-snap. The old URLs (which were without slashes) are now redirecting to new URLs with slashes. For example: This URL: ...

Exploring alternative methods for accessing object values in TypeScript using a string object path without relying on the eval function

If we have an object in JS/typescript structured like this: var obj = { a: { b:{ c:1 } } } And a string "b.c" is given, how can we evaluate this using only the variables provided and retrieve the value 1 from the object without rel ...

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...

Developing web components using angular.js while ensuring compatibility with IE11

I have an angular.js application where I need to initialize a web component. Everything runs smoothly on different browsers, however IE11 seems to have problems with document.importNode The angular.js onInit function is as follows: vm.$onIni ...

Unable to activate primary error handler in my Node.js Express application

I have implemented node express (4.15.2) and used the default error handler provided by the express generator function to manage errors. Here is the code snippet: const app = express(); app.set('port', config.enviroment.portNumber); app.use(log ...

The date displayed on the popup calendar is local time, while the date selected is in Coordinated

Is there a way to maintain the selected date in UTC format? I am experiencing an issue where the pop-up calendar does not synchronize with the selected datetime. For instance, when I click on 08/13 and the selected date shows as 08/12. This discrepancy ...

Designing Checkbox features with Bootstrap Glyphicons

I have successfully created a set of bootstrap icons functioning as radio buttons. Now, I am trying to achieve a similar effect with checkboxes, allowing users to select and store multiple options. I am struggling to figure out the best approach to impleme ...

What methods can be used to modify the appearance of the cursor depending on its position?

Is there a way to change the cursor to a left arrow when on the left half of the screen and switch it to a right arrow when on the right half, using JavaScript? I am trying to achieve something similar to what is shown on this website. I attempted to acco ...

The endpoint successfully responds with a 302 status code when using an AJAX-enabled class-based

I've been experimenting with implementing login and logout forms using ajax in django. My goal is to encapsulate the standard auth login and logout functionality into an ajax-enabled class-based view. The GET request is working fine, but for some reas ...

The print preview displays a single div in an incorrect location

I have successfully created a javascript plot and wanted to incorporate a legend that overlaps the plot. Unfortunately, the function I used does not support directly overlapping legends, but it does allow for placing the legend in a separate div. To work a ...