0

I've searched for an answer for my particular predicament and I reckon it must have something to do with misunderstandings of my own (I'm new to JS). I know of similar topics but not quite addressing what I'd like to pin down - please forgive me if I have missed something previously posted.

I have boiled down what I'm trying to do to the following JavaScript which draws on jQuery's get to read file contents to a variable (I was trying to avoid all the hullabaloo involved in using XMLHttpRequest() just to read a file server-side):

window.onload = function(){

var refFile = "./myFile"; // path to my txt file
var fileContent;

    $.get(refFile, function(response) {
         fileContent = response;
         alert(fileContent);  // I get data here just fine
    });

    alert(fileContent);          // undefined here - how can I have fileContent defined here?

}

If it's preferable to use XMLHttpRequest in pure JS instead that's fine, but I'd just like to know how to be able to make the value live outside the retrieving function - for use with other functions, for instance.

Any ideas on what I'm missing?

Any help would be much appreciated.

devEngine
  • 3
  • 2
  • 3
    The jQuery $.get function is asynchronous. So, the code inside is running after the $.get request happens but JavaScript moves on to the next command while running asynchronous commands. The 2nd alert runs before the $.get is finished. Is that the confusion? – Cody Brumfield May 30 '17 at 23:39
  • I see - yes, indeed. Completely forgot about the async issue. Thank you very much! – devEngine May 30 '17 at 23:42

2 Answers2

-1

The $.get() function works asynchronous, so the fileContent doesn't contain the response because of this.

window.onload = function(){

  var refFile = "./myFile"; // path to my txt file
  var fileContent;

  $.get(refFile, function(response) {
    // do something here
  }).done(function(response){
    fileContent = response;
  });

  alert(fileContent); // not undefined anymore

}

Take a look at the documentation

Edson Dota
  • 383
  • 4
  • 6
  • Thanks for this - I tried this myself as well, but it doesn't seem to work. Really not sure why, though. – devEngine May 30 '17 at 23:54
-2

This code should work for you.

var refFile = "./myfile"; // path to my txt file
function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', refFile, true);
xhr.send(null);
Damien
  • 1,582
  • 1
  • 13
  • 24