Tomas Lucena
Tomas Lucena

Reputation: 1526

Javascript file reader does not get stored in array

I am trying to upload multiple images. So I read that I can generate a temporary url and send them with ajax.

The idea is push the url created with filereader into an array and the send with ajax but the url's are not pushed properly. When I see the result I got like an empty array:

enter image description here

But if I click the arrow I can see the url's inside

enter image description here

But them seems Inaccessible.

This is my code:

$('form').on('submit',function(e) {

        e.preventDefault();

        var filesToUpload = document.getElementById("myFile");
        var files = filesToUpload.files;
        var fd = new FormData();
        var arr = [];

        if (FileReader && files && files.length) {

            for (i=0; i< files.length; i++){


                (function(file) {

                    var name = file.name;
                    var fr = new FileReader();  


                    fr.onload = function () {

                            arr.push(fr.result);

                    }

                    fr.readAsDataURL(file);

                })(files[i]);

            }

            console.log(arr);

        }


    });

The final idea is convert to string JSON.stringify(arr) and then parse in php json_decode($_POST['arr']).

Of course this is not working because JSON.stringify(arr) gets empty.

Upvotes: 0

Views: 1000

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Maybe the following simple solution works for you? I placed your console.log() and your ajax call into the fr.onload() method but fire it only, after your results array has been filled up with all values:

$('form').on('submit',function(e) {
        e.preventDefault();
        var filesToUpload = document.getElementById("myFile");
        var files = filesToUpload.files;
        var fd = new FormData();
        var arr = [];
        if (FileReader && files && files.length) {
            for (var i=0; i< files.length; i++){
                (function(file) {
                    var name = file.name;
                    var fr = new FileReader();  
                    fr.onload = function () {
                            arr.push(fr.result);

                            if(arr.length==files.length) {
                              console.log(arr);
                              // place your ajax call here!
                            }
                        }
                       fr.readAsDataURL(file);
                })(files[i]);
            }
        }
});

Upvotes: 2

Related Questions