Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable outside onload XMLHttpRequest [duplicate]

I have this XMLHttpRequest and I want to print the variable contents... But outside function onload the variable contents is "". How I can access the variable outside the function?

var xhr = new XMLHttpRequest();
var contents = ""
xhr.open("GET", fileURL);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response], {type: "application/pdf"});
        var objectUrl = URL.createObjectURL(blob);
        alert("sucess")

        var reader = new FileReader();
        reader.readAsBinaryString(blob);
        reader.onload = function(e) {
            contents = e.target.result;
        }
    }
    else {
    alert("insucess");
    }
};
xhr.send();


console.log(contents);
like image 664
PRVS Avatar asked Oct 15 '25 21:10

PRVS


1 Answers

A better option is to execute a function with the response as a callback.

A quick example:

var createXhrRequest = function( httpMethod, url, callback ) {

    var xhr = new XMLHttpRequest();
    xhr.open( httpMethod, url );

    xhr.onload = function() {
        callback( null, xhr.response );
    }; 

    xhr.onerror = function() {
        callback( xhr.response );
    };

    xhr.send();

}

createXhrRequest( "GET", fileUrl, function( err, response ) {

    // Do your post processing here. 
    if( err ) { console.log( "Error!" ); }

    // This is just basic code; you can modify it to suit your needs.

});

Remember, using async is better than using a Hacked-Sync method.

EDIT 1: Based on what you want

That is something you shouldn't do. I got what you're trying to say; for that, you'll need sync XMLHttpRequests which aren't advisable.

Remember the way Async (threading) works on PARALLEL threads, so any async activity will have its own thread, rather than working on the same thread.

But again, I'll recommend async requests. A great way to do it is to use the Promises.js Library availble at https://www.promisejs.org/

In simple terms, you can't do that easily.

like image 117
weirdpanda Avatar answered Oct 18 '25 11:10

weirdpanda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!