Kenziiee Flavius
Kenziiee Flavius

Reputation: 1949

Pass input file data to PHP(Laravel) Using Javascript (VueJs)

Quite simply im trying to pass a file from javascript to PHP using javascript, Ive tried the following but its not picking up the file that ive inputted.

My Html

    <form v-on:submit="submitForm($event)">
        <input type="file" id="image" v-el="fileInput">
        <button class="btn">
            Submit
        </button>
    </form>

My JavaScript

methods: {
        submitForm: function(e) {
                e.preventDefault();

                var formData = new FormData();
                formData.append('image', $('#image').files[0]);

                console.log(formData);

                this.$http.post('getFiles', formData, function (data, status, request) {
                    console.log('success');
                }).error(function (data, status, request) {
                    console.log('error');
                });
            }
        }

And lastly The Error

TypeError- Cannot read property '0' of undefined

Im not 100% sure whats the problem here but it doesnt seem to be registering when i upload a file, any help would be appreciated

Upvotes: 1

Views: 530

Answers (1)

Rwd
Rwd

Reputation: 35180

$('#image') is going to return an array.

So, to get it to work you can:

$('#image')[0].files[0]

Hope this helps!

Upvotes: 1

Related Questions