njp
njp

Reputation: 705

How to cleanly get a text file using AJAX request

See the code below. When the request is sent and comes back OK, in the reqListener() function, I get the contents of my text file output.

However, when I try to return the response variable later, it's still undefined, as if reqListener() hasn't been called yet. Could this be due to the async=true argument?

Furthermore, is there a neater way to get the response text out of the function should it the request be successful, like using a closure?

function load_text_file()
{
    function reqListener() {
        if (this.readyState == 4 && this.status == 200)
        {
                response = this.responseText;
                console.log(response);
        }
    }

    var response;
    var oReq = new XMLHttpRequest();
    oReq.onreadystatechange = reqListener;
    oReq.open("get", "file.txt", true);
    oReq.send();
    return response;
}

var TEXT = load_text_file();
console.log(TEXT);

Upvotes: 0

Views: 1259

Answers (1)

Tom Elmore
Tom Elmore

Reputation: 1980

The request will take time to complete. You would be better off handing in a callback which fires when the file has loaded:

function load_text_file(callback)
{

    function reqListener() {

        if (this.readyState == 4 && this.status == 200)
        {
                console.log(response);
                callback(this.responseText);

        }
    }


    var oReq = new XMLHttpRequest();
    oReq.onreadystatechange = reqListener;
    oReq.open("get", "file.txt", true);
    oReq.send();
}

load_text_file(function(){
    console.log(TEXT);
});

Upvotes: 1

Related Questions