0

Im trying to get dropzone.js working with multiple input and select fields working.

Also reading the dropzone.js documentation i saw that the dropzone form looks like a stand alone form. So when i tried to add more input and select fields inside the dropzone form, the complete form gets covered by a dropzone, and i wanted just one part to be a dropzone. Also i found i way fixing it reading other stackoverflow articles.

What i did is i created a form with 3 input fields, 7 select options and + 1 dropzone, and i have 1 submit button which should submit it all together.

I have followed this stackoverflow article: Integrating Dropzone.js into existing HTML form with other fields

Problem: When I submit the form the file starts uploading (Progress animation shows it) but the file gets not uploaded to the server, and the form gets not completly submited, also the fields values are not sent to the database.

This is the form start code:

<form  id="drform" name="formapdf2" method="post" action="dodaj-save.php" autocomplete="off" enctype="multipart/form-data">

This is the submit button code:

<button id="sbmtbutton" class="btn btn-primary" name="insert" type="submit">Registruj radnika</button>

Here is the JS code i use:

Dropzone.options.dropfile = {
    acceptedFiles: 'image/*',
    maxFiles: 1,
    resizeWidth: 300,
    resizeHeight: 300,
    resizeMethod: 'contain',
    resizeQuality: 1.0,
    maxFilesize: 4,
    autoProcessQueue: false,
    url: 'dodaj-save.php',
    addRemoveLinks: true,
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("sbmtbutton").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("name", jQuery("#dzfname").val());
            formData.append("qrcode", jQuery("#dzfqrcode").val());
            formData.append("company", jQuery("#select_id").val());
            formData.append("money", jQuery("#dzfmoney").val());
            formData.append("checkin", jQuery("#dzfcheckin").val());
            formData.append("checkout", jQuery("#dzfcheckout").val());
            formData.append("checkin1", jQuery("#dzfcheckin1").val());
            formData.append("checkout1", jQuery("#dzfcheckout1").val());
            formData.append("checkin2", jQuery("#dzfcheckin2").val());
            formData.append("checkout2", jQuery("#dzfcheckout2").val());
        });
    }
}

I have the PHP code for upload too, but im not sure if the php code is the problem, and should i show this code too here. If you need anything else to identify what is the problem please let me know. And I hope i didnt break any stackoverflow rule since this is my first post.

Elvedin S
  • 21
  • 1
  • 1

1 Answers1

1

Try this. It's a little different from how you are doing it, but it works really well.

First thing you can do is to stop Dropzone.js from auto detecting the the form tags by adding this outside of your $(document).ready(function(){}):

Dropzone.autoDiscover = false;

Then create the Dropzone instance with the AJAX function. Do this inside of the $(document).ready(function(){}), but outside of the button click event:

let myDropzone = new Dropzone('.dropzone', { //Give your input (or form if you're not sending anything else) a class of dropzone
    autoProcessQueue: false,
    acceptedFiles: ".svg", // Add accepted file types here
    url: "dodaj-save.php", // Your PHP file here
    init: function() {
        this.on("addedfile", function() {
            //Do something before the file gets processed.
        })
        this.on("sending", function(file, xhr, formData){
            //Do something when the file gets processed.
            //This is a good time to append additional information to the formData. It's where I add tags to make the image searchable.
            formData.append('tags', 'cat-cats-kittens-meow')
        }),
        this.on("success", function(file, xhr) {
            //Do something after the file has been successfully processed e.g. remove classes and make things go back to normal. 
        }),
        this.on("complete", function() {
            //Do something after the file has been both successfully or unsuccessfully processed.
            //This is where I remove all attached files from the input, otherwise they get processed again next time if you havent refreshed the page.
            myDropzone.removeAllFiles();   
        }),
        this.on("error", function(file, errorMessage, xhr) {
            //Do something if there is an error.
            //This is where I like to alert to the user what the error was and reload the page after. 
            alert(errorMessage);
            window.location.reload();
        })
    }
});

Then loop through all the attached files and process all of them consecutively when the submit button is clicked:

const uploadBtn = document.querySelector('#sbmtbutton');
uploadBtn.addEventListener('click', () => {
    const acceptedFiles = myDropzone.getAcceptedFiles();
    for (let i = 0; i < acceptedFiles.length; i++) {
        myDropzone.processFile(acceptedFiles[i])
    }
})

That is all from the Javascript side. In your PHP file you can process the files and move it to a folder on the server:

<?php

    $folder_name = 'path-to-your-folder/';

    if (!empty($_FILES)) {
        $temp_file = $_FILES['file']['tmp_name'];
        $filename = $_POST['tags'].'.svg'; //Grabbing those tags that I appended to formData in the AJAX request and renaming the file based on those tags. Be sure to add your image extension
        $location = $folder_name.$filename;
        move_uploaded_file($temp_file, $location);
    }

?>

I hope this helps! =) It's also important to note that you would have to run this on a local server if you want the PHP to run when you are testing this on your local machine. You can set up a local server by following these instructions.

You can use PHP and JS to bring the images back from the server and display it on the client side, but that might be beyond the scope of this question. If you want me to add it, just mention it in a comment an I'll add it as an update to the answer.

Ludolfyn
  • 1,806
  • 14
  • 20