Search code examples
javascriptxmlhttprequestreturn-value

How to return the result from XMLHttpRequest?


I have following function to convert local file to base64. When I run it, it writes the result (res) to console. How can I return the content of res from the function, so I can use it in another one?

function convertToBase64() {
    var xhr = new XMLHttpRequest();       
        xhr.open("GET", "1.jpg", true); 
        xhr.responseType = "blob";
        xhr.onload = function (e) {
            var reader = new FileReader();
            reader.onload = function(event) {
               var res = event.target.result;
               console.log(res);
        }
        var file = this.response;
        reader.readAsDataURL(file)
    };
    xhr.send()
}

(I am totally new in JavaScript.)


Solution

  • you can pass callback to your function to execute when file loaded

    function convertToBase64(onLoad) {
        var xhr = new XMLHttpRequest();       
            xhr.open("GET", "1.jpg", true); 
            xhr.responseType = "blob";
            xhr.onload = function (e) {
                var reader = new FileReader();
                reader.onload = function(event) {
                   var res = event.target.result;
                   console.log(res);
                   onLoad(res);            // callback
            }
            var file = this.response;
            reader.readAsDataURL(file)
        };
        xhr.send()
    }
    

    now you can do this :

    convertToBase64(function(res) {
        console.log('response loaded' , res);
    });