Is there a way to access the value of a variable that is defined in FileReader.onloadend from within the callback function of XMLHttpRequest.onreadystatechange

I'm trying to access the value of the variable ext (defined within the function reader.onloadend) in the function xhr.onreadystatechange. Currently, it is returning undefined. Does anyone have any suggestions on how to resolve this issue?

function process_file(file_input) {
  var name = file_input.dataset.target;
  var url = file_input.dataset.url;
  var path = file_input.dataset.path;
  var ext;

  for(var i = 0; i<file_input.files.length; i++) {
    var file = file_input.files[i];
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var id = xhr.responseText;
            var input = document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", name);
            input.setAttribute("value", id);
            document.getElementById("btn_uload_"+name+"_"+ext).append(input);
            document.getElementById("empty_file").style.display = 'none';
            document.getElementById("single_file_"+ext).style.display = 'block';
        }
    };
    var reader  = new FileReader();
    reader.onloadend = function() {
      var bytes = reader.result;
      ext = file.name.split(".").pop();
      var formData = new FormData();
      formData.append('bytes', bytes);
      formData.append('type', ext);
      xhr.send(formData);
    }
    reader.readAsDataURL(file);
  }
}

Answer №1

To fix the issue of creating a local variable instead of setting an external one, remove the var ext =... from the reader callback function. Even if you eliminate the var keyword, attempting to set the external ext variable may lead to complications as discussed in this Stack Overflow post

To address this concern, move the assignment to the top of the loop (not the function) and utilize let instead of var for block scoping. This approach will prevent running into the aforementioned issue.

for(let i = 0; i<file_input.files.length; i++) {
    var file = file_input.files[i];
    let ext = file.name.split('.').pop();

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

Issue with tensorflow.js multiple regression stochastic gradient descent optimization

Greetings, everyone! I have recently encountered a perplexing issue while attempting to fit a curve in tensorflow.js. Despite spending a considerable amount of time on it over the past couple of days, I haven't been able to resolve it yet. Given that ...

The Node.js Express server seems to be having trouble accessing static files

After successfully starting the express server, I encountered an issue when trying to load static files which resulted in an error message reading "Cannot GET /URL". The static files are located within a folder named "Login" and both the app.js and "Logi ...

What is the best way to manage zoom settings following a completed search query?

Whenever I try to search for an address using this map, it zooms in way too much making the map unusable. Despite my efforts to adjust the map bounds, I have not been successful. It seems like I am on the right track but for some reason, it just isn't ...

Struggling with deploying Next.js on Vercel

Encountered an issue while trying to deploy a project on Vercel. The error message is as follows: fileName: comps/Navbar.js imported as import Navbar from "./Navbar"; 16:36:51 ModuleNotFoundError: Module not found: Error: Can't reso ...

What is the best way to transform a collection of items into FormData?

In my current project, I have a JavaScript array structured as follows: var items = [{ ID: "1" count:'1', File: (binary file) }, { ID: "2" count:'2', File: (binary file) } ] My goal is to ...

Utilizing functions for object creation in JavaScript

Having trouble with creating a function that automatically generates an object and then alerts its properties. Can't seem to get the alerts when I click the button. Any assistance would be appreciated. <html> <head> <s ...

Having trouble activating the submit function using an external JavaScript file

Having trouble getting the form to submit properly. I have placed the form inside a <div id="access"></div> by setting its innerHTML using an included js file in the header of the page. Here's how it looks: <div id="access"> < ...

What is the process for adding elements to an object in Angular JS?

My goal is to send data to an ng-object after filling out and submitting an HTML form with user-defined values. However, after pressing submit, the values are being duplicated. I have attempted to clear the data by using $scope.user > $scope.user=&apos ...

Struggling to retrieve an element from an object received through a get request in Express

I am facing an issue with a get request that returns an array of objects retrieved from a database using Knex. I am trying to use .map to make these objects accessible, but I am struggling with accessing the final element which is a sum(). It seems like a ...

Encountering issues while attempting to execute node-sass using npm

Currently, I'm attempting to execute node-sass using npm. Displayed below is my package.json: { "name": "my-project", "version": "1.0.0", "description": "Website", "main": "index.js", "scripts": { "sass": "node-sass -w scss/ -o dist ...

Put dashes in the middle of each MongoDB post title

In my express app, users can create and view posts. Currently, I search for posts by their title. However, I am encountering an issue when the post title contains spaces. The search function works perfectly for titles without spaces, but it gives an error ...

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

Implementing onClick functionality in RecyclerView post JSON data extraction

I recently implemented a RecyclerView in a fragment and successfully parsed JSON data from a website to display it in the RecyclerView following a helpful tutorial found at: Now, my next challenge is adding an onClick listener to the items in the Recycler ...

"Transforming the Website Background with a Splash of Color

I am trying to figure out how to change the color scheme of my website with a button click. Currently, when I select a different color, only the background of the webpage I'm on changes, not the entire website. I have applied CSS but it's not ref ...

Does anyone have any sample code on processing JSON data from a URL using Modified JavaScript Value in Java?

Could anyone provide some examples on how to handle returned Json data using Modified JavaScript Value? Here is the specific data I require from the json url: { "result": { "data": [ { "name": "page1", "period": "dia", "values": [ { "value": 4, "end_time" ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

Issue with Datepicker not updating when triggered by event handler

Having an issue with my material-UI datepicker where the date is not updating correctly when I try to select a new one. The initial value set in useState works fine, but I want the datepicker to smoothly update when I choose a different date. You can see a ...

Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there. I am curious to know how I can transform the code below from an OnClick event to a timed event. For instance, I would like to refres ...

Error encountered: Scrollanimation IOS syntax error- Unexpected token '=.' an open parenthesis '(' was expected before a method's parameter list

Encountering an issue with the scroll animation on older IOS devices (2019 and older) - I receive the following error message: SyntaxError: Unexpected token '='. Expected an opening '(' before a method's parameter list. class Event ...

Is there a way to incorporate a computed value into a table prop while working with Element UI?

In my frontend development, I am utilizing vuejs along with element ui. I am faced with the task of rendering a table that includes dates in unix format. To make these dates more user-friendly, I have incorporated moment.js to convert them into a readable ...