0

I am working on a html project in which the user uploads a txt file whose content is further processed and the result shown. The upload and processing step works fine but somehow the result is never shown. The (for me) confusing part is that if I add an alert() between processing and result presentation, the result is then displayed correctly.

Is this a known issue that I am missing?

In the code example bellow, if you remove the commentary on the alert(), the result is displayed correctly in the "demo" paragraph. But without it, nothing is shown.

I'd be grateful for either an explanation of my mistake or an alternative solution.

Thank you very much!

function myFunction() {
  var x = document.getElementById("file");
  var textFromFileLoaded = "";
  if (x.value != "") { // text upload
    var file = x.files[0];
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) {
      textFromFileLoaded = fileLoadedEvent.target.result;
    }
    fileReader.readAsText(file, "UTF-8");
  }
  //alert("somth"); //HERE
  document.getElementById("demo").innerHTML = textFromFileLoaded;
  return true;
}
Select a file to upload:
<input type="file" id="file" size="50" accept="image/*">
<button onclick="myFunction()">button</button>
<p id="demo"></p>

1 Answer 1

1

You should put document.getElementById("demo").innerHTML = textFromFileLoaded; inside the onload function

fileReader.onload = function(fileLoadedEvent) {
  textFromFileLoaded = fileLoadedEvent.target.result;
  document.getElementById("demo").innerHTML = textFromFileLoaded;
}

Filereader is asynchronous so when you add the alert you give your code enough time to call onload before you add the text into the demo element. Without the alert textFromFileLoaded is not set (from the onload function) when you add it to the demo element

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.