1

I'm trying to post an image and some text via ajax onto my laravel server except I can't seem to add the File into the ajax request.

I have tried making a FormData and appending the needed params, I also tried serializing my form with jQuery.

$("#create-post-button").click(function(){
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

        // var formData = new FormData();
        // formData.append('src', $('#src')[0].files[0]);
        // formData.append('title', $);
        // formData.append('_token', CSRF_TOKEN);
        // formData.append('_method', 'POST');

        event.preventDefault();

        console.log($('#src')[0].files[0]);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': CSRF_TOKEN
            },
            url: '/posts/create',
            type: 'POST',
            data:
            {
                '_method': 'POST',
                '_token': CSRF_TOKEN,
                'title':$("#title").val(),
                'src': {
                    'name':$('#src')[0].files[0].name,
                    'size':$('#src')[0].files[0].size
                }
            },
            dataType: 'json'
        });
    });

I expect that when I dump my $request in laravel, that it has the correct request params but also including the $file (FileBag) param for the file that is being posted.

EDIT: I have looked up the link @charlietfl provided in the comments and it helped me a lot, so here is the end result:

$("#create-post-button").click(function(){
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

        event.preventDefault();

        var file_data = $('#src').prop('files')[0];
        var form_data = new FormData();
        form_data.append('_method', 'POST');
        form_data.append('_token', CSRF_TOKEN);
        form_data.append('title', $('#title').val());
        form_data.append('src', file_data);

        $.ajax({
            url: '/posts/create',
            dataType: 'text',
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function(){
                showSuccessUploadingPost();
            },
            error: function() {
                showErrorUploadingPost();
            }
        });
    });
  • You were on the right track using `FormData`. You need that to upload files. See ajax config here https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php – charlietfl Apr 08 '19 at 21:17
  • @charlietfl I looked at the post and it helped it out I figured it out what I was doing wrong, kinda. – ToastyTeddy Apr 09 '19 at 09:29

1 Answers1

1

The CSRF token at file upload required to pass as a GET parameter.

$("#create-post-button").click(function(){
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    var form_data = new FormData();
    form_data.append('title', $('#title').val());
    jQuery.each(jQuery('#src')[0].files, function(i, file) {
        data.append('src', file); //use the following line to handle multiple files upload
        // data.append('src' + i, file);
    });

    $.ajax({
        url: '/posts/create?_token=' + CSRF_TOKEN,
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        method: 'POST',
        type: 'POST', // For jQuery < 1.9
        success: function(){
            showSuccessUploadingPost();
        },
        error: function() {
            showErrorUploadingPost();
        }
    });  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form id="uploadFrm" enctype="multipart/form-data" method="post">
    <input type="file" name="src" />
    <button id="create-post-button">Upload</button>
</form>
Miller Cy Chan
  • 897
  • 9
  • 19
  • I tried it, changed #results to #uploadFrm and X-CSRF-TOKEN to _token, but I get an response error that the title and src is required. If I check the request I received It doesn't have the File with it and the src is empty. – ToastyTeddy Apr 09 '19 at 08:50