Drewlim7's avatar

Controller received empty data using AJAX and dropzone.js

Hi I am using dropzone.js to upload images together with existing formdata. I managed to combine both of them and using ajax to post if dropzone is empty. However, when I uploaded an image and send it to my controller with the existing form data, and i used dd($request->all()); to output the data but all I received was an empty array []. I even dd $request and I realised filebag and parameterbag are empty... Moreover, I did check developer networking tab, the post request does contain all of the params and file (dropzone.js) to my controller but my controller cannot output any of it.

Here is my partial js code.

Dropzone.autoDiscover = false;
    var current = $('.form_id').val();
    $("div#myId").dropzone({         
        url: "/custom/"+current,
        addRemoveLinks: true,
        uploadMultiple: true,
        autoProcessQueue: false, // this is important as you dont want form to be submitted unless you have clicked the submit button
        // autoDiscover: false,
        method: 'PATCH',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        // paramName: 'pics', // this is optional Like this one will get accessed in php by writing $_FILE['pic'] // if you dont specify it then bydefault it taked 'file' as paramName eg: $_FILE['file'] 
        // previewsContainer: '#dropzonePreview', // we specify on which div id we must show the files
        clickable: true, // this tells that the dropzone will not be clickable . we have to do it because v dont want the whole form to be clickable 
        dictDefaultMessage: "Upload images here",
        maxFilesize: 3, // MB
        maxFiles: 10,
        acceptedFiles: ".jpeg,.jpg,.png",
        timeout: 60000,
        accept: function(file, done) {
            console.log("uploaded");
            done();
        },
        error: function(file, msg){
            console.log(msg);
        },
        init: function() {
            var myDropzone = this;
            //now we will submit the form when the button is clicked
            $("#btn-edit-form-two").on('click',function(e) {
               e.preventDefault();
               e.stopPropagation();
               $('#btn-edit-form-two').prop('disabled', true);
                var form = $(this).parents('form');
                var next_step = true;
                var current = $('.campaign_form_id').val();
                if($(form)[0].checkValidity()) { 
                    
                    if(next_step == true){

                        if (myDropzone.getQueuedFiles().length > 0) {                        
                            myDropzone.processQueue();  
                            console.log("sending now with dropzone");
                        } else {                       
                            $.ajax({
                            type: "POST",
                            url: "/custom/"+current,
                            data: new FormData($(form)[0]),
                            processData: false,
                            contentType: false,
                            success: function(msg) {
                                if(msg != ""){
                                    window.location.href = msg;
                                }
                            },
                            error: function (msg) {
                                var errors = msg.responseJSON;
                                errorsHtml = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>×</button>";
                                
                                if(errors.errors != "" && errors.errors != undefined && errors.message != "") {
                                    
                                    $.each(errors.errors, function (key, data) {
                                        $.each(data, function (index, data) {
                                            errorsHtml += '<p class="mb-0">'+ data + '</p>';
                                        });
                                    });

                                } else if (errors.message != "" && errors.message != undefined){
                                    $.each(errors.message, function (key, data) {
                                        errorsHtml += '<p class="mb-0">'+ data + '</p>';
                                    });
                                }
                                errorsHtml += "</div>";
                                $('#edit-feedback-two').html(errorsHtml);
                                $('#edit-feedback-two').show();
                                $('#btn-edit-form-two').prop('disabled', false);
                            }
                        });
                            console.log("sending now without dropzone");
                        }
                        
                        // myDropzone.processQueue(); // this will submit your form to the specified action path
                    }
                }
                else {
                    $(form)[0].reportValidity();
                    $('#btn-edit-form-two').prop('disabled', false);
                }
               // after this, your whole form will get submitted with all the inputs + your files and the php code will remain as usual 
               //REMEMBER you DON'T have to call ajax or anything by yourself, dropzone will take care of that
            });
            
            // this.on("sending", function(file, xhr, formData){
                // $("#edit-form-two").find("input").each(function(){
                //     formData.append($(this).attr("name"), $(this).val());
                // });
            // });
            this.on("sendingmultiple", function(file, xhr, formData) {
            // Gets triggered when the form is actually being sent.
            // Hide the success button or the complete form.
            $("#edit-form-two").find("input").each(function(){
                    formData.append($(this).attr("name"), $(this).val());
                    console.log($(this).attr("name") + " "+ $(this).val());
                });
            });
            this.on("successmultiple", function(files, response) {
            // Gets triggered when the files have successfully been sent.
            // Redirect user or notify of success.
            });
            this.on("errormultiple", function(files, response) {
            // Gets triggered when there was an error sending the files.
            // Maybe show form again, and notify user of error
            });
        } // init end

    });

Here is my partial html code,

<form id="campaign-edit-form-two" method="POST" action="/custom/{{$form_id}}" enctype="multipart/form-data">
@csrf
@method('PATCH')

<div class="dropzone" id="myId">
    <div class="fallback">
        <input id="files" multiple="true" name="files[]" type="file">
    </div>
</div>
0 likes
1 reply
Drewlim7's avatar

I found a solution. I just replaced the method from "PATCH" to "POST" and its working. Sorry for being clumsy.

Please or to participate in this conversation.