Search code examples
javascriptjquerydomget

Fetching local text file and assign contents to a variable


For as simple as this should be, I have no idea what I am doing wrong. I'm attempting to fetch a local text file and store it in a variable, but regardless of the method (fetch api, $.get and ajax) I use, I always get undefined.

$(document).ready(function() {

    var fileConfiguration;

    $.get( "Configuration.h", function( data ) {
        fileConfiguration = data;
    });
    
    document.getElementById("demo").innerHTML = fileConfiguration;

});

The data variable is properly fetched, I can use alert or console.log and see the contents correctly. When I assigned it to a variable though, it's undefined. I imagine this has something to do with it being an asynchronous callback, but can't figure out the problem.


Solution

  • As you and @charlietfl have pointed out the AJAX request is asynchronous which means that the last statement in your code is executed before there's a response, hence fileConfiguration is still undefined.

    Therefore the best place to do the assignment is inside the callback like so:

    $(document).ready(function() {
        $.get( "Configuration.h", function( data ) {
            document.getElementById("demo").innerHTML = data;
        });
    });