0

I'm calling a function to encode in base64 an image, this function works because when I console.log the result IN the function, I do have a result. But when i try to get the result in an other function, the returned result is : "undefined".

Here is my javascript :

console.log(loadImageFileAsURL());

function loadImageFileAsURL(){
    var filesSelected = document.getElementById("inputFileToLoad").files;

    if (filesSelected.length > 0){
        var fileToLoad = filesSelected[0];
        var fileReader = new FileReader();

        fileReader.onload = function(fileLoadedEvent){
            var result = fileLoadedEvent.target.result;

            //console.log(result) ; => gives a result
            return (result) ;
        };
        fileReader.readAsDataURL(fileToLoad);
    }
}

[EDIT]=> Response @ Variable doesn't get returned from AJAX function

Here is my call :

loadImageFileAsURL(function test(res){
    console.log("===>:"+res);
});

Here is my function :

function loadImageFileAsURL(callback){
    var filesSelected = document.getElementById("inputFileToLoad").files;

    if (filesSelected.length > 0){
        var fileToLoad = filesSelected[0];
        var fileReader = new FileReader();

        fileReader.onload = function(fileLoadedEvent){
            var result = fileLoadedEvent.target.result;
            callback(result);
        };
        fileReader.readAsDataURL(fileToLoad);
    }
}
Community
  • 1
  • 1
Gauthier
  • 1,116
  • 2
  • 16
  • 39
  • 1
    See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Denys Séguret Nov 04 '14 at 14:49
  • It did not think that it is the same question... So what is the answer ? I am doing an Ajax call ? – Gauthier Nov 04 '14 at 15:03
  • The problem is asynchronicity. See also [this QA](http://stackoverflow.com/questions/12475269/variable-doesnt-get-returned-from-ajax-function) which will probably be simpler to understand and apply – Denys Séguret Nov 04 '14 at 15:05
  • I didn't know it, i'll probably be ban because of my questions, why you just didn't tell me "Asynchronicity problem" instead of sending me in an other question and mark mine as duplicate ?! And I don't know what should I modify to make it works... I don't see any similarity betwin both posts. – Gauthier Nov 04 '14 at 15:10
  • I didn't downvote your question, I just marked it as duplicate to reduce redundancy. – Denys Séguret Nov 04 '14 at 15:14
  • Here's an upvote because your question is clean. – Denys Séguret Nov 04 '14 at 15:14
  • Ok, thanx but, I'm not that good in javascript. Is it realy asynchronous ? I look in the other post for how to return the result but I still dont find... – Gauthier Nov 04 '14 at 15:17
  • Look at my answer (http://stackoverflow.com/questions/12475269/variable-doesnt-get-returned-from-ajax-function) – Denys Séguret Nov 04 '14 at 15:24
  • Thanx for help. I made it work. I updated my post with the answer. – Gauthier Nov 04 '14 at 17:19

0 Answers0