Ajax Image Upload Using Dropzone.js with Normal Form Fields On Button Click Using PHP

Posted by & filed under Ajax, CSS, HTML5, JAVASCRIPT, JQUERY, MYSQL, PHP.

In this tutorial we are going to see how to combine normal form fields with image upload using Dropzone.js, PHP, jQuery and Ajax on button click. Using Dropzone.js only image upload via Ajax is very easy, But when we want to send normal form data along with image via Ajax is little bit extra effort we need to put on configuration side. Let see how to configure Dropzone.js in this tutorial step by step.

Ajax Image Upload Using Dropzone js with Normal Form Fields On Button Click Using PHP
You may refer this initial tutorial ajax image/file upload using DropzoneJS & PHP

Ajax Drag And Drop Image/File Upload Using DropzoneJS, PHP

 

Step 1: Create HTML5 Form and Add Required JS and CSS Files:

In this tutorial we are going to use following mandatory libraries.

  1. DropZone.js
  2. jQuery

Following are optional libraries that we are using for just styling pages and validating the HTML5 form.

  1. Bootstrap 4
  2. jQuery Validation

First create index.html file and add the following base html in it.


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax Image Upload Using Dropzone.js with Normal Form Fields On Button Click Using PHP</title>
</head>
<body>
    
</body>

</html>

Next add required CSS and JS files in it. CSS files in <head> section and JS files before closing </body> tag.


    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/dropzone.css">
    <link rel="stylesheet" href="./css/style.css">

    
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="./js/jquery.validate.min.js"></script>
    <script src="./js/dropzone.js"></script>
    <script src="./js/script.js"></script>

Step 2: Design HTML5 Form With DropZone.js Placeholder:

Here is the HTML5 form markup with DropZone.js placeholder ( <div> ). Add the following HMTL5 form in your index.html file.


<form id="imageUploadForm">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" name="name" id="name" aria-describedby="name" placeholder="Enter Name">
        <small class="form-text"></small>
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" name="email" id="email" placeholder="Email">
        <small class="form-text"></small>
    </div>
    <div class="form-group">
        <label for="mobile">Mobile</label>
        <input type="text" class="form-control" name="mobile" id="mobile" aria-describedby="mobile" placeholder="Enter mobile">
        <small class="form-text"></small>
    </div>
    <div id="imageUpload" class="dropzone"></div>
    <button id="uploaderBtn" type="button" class="btn btn-primary">Save</button>
</form>

Step 3: Initialize DropZone.js Image Upload Programatically:

If you add class name dropzone in any of the HMTL5 element. DropZone.js automatically initialize image uploader, but we are disabling the auto initialization of DropZone.js using


Dropzone.autoDiscover = false;

Here is JS Script which initialize DropZone.js programmatically with all configurations required.


myDropzone = new Dropzone('div#imageUpload', {
    addRemoveLinks: true,
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 3,
    paramName: 'file',
    clickable: true,
    url: 'ajax.php',
    init: function () {

        var myDropzone = this;
        // Update selector to match your button
        $btn.click(function (e) {
            e.preventDefault();
            if ( $form.valid() ) {
                myDropzone.processQueue();
            }
            return false;
        });

        this.on('sending', function (file, xhr, formData) {
            // Append all form inputs to the formData Dropzone will POST
            var data = $form.serializeArray();
            $.each(data, function (key, el) {
                formData.append(el.name, el.value);
            });
            console.log(formData);

        });
    },
    error: function (file, response){
        if ($.type(response) === "string")
            var message = response; //dropzone sends it's own error messages in string
        else
            var message = response.message;
        file.previewElement.classList.add("dz-error");
        _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            node = _ref[_i];
            _results.push(node.textContent = message);
        }
        return _results;
    },
    successmultiple: function (file, response) {
        console.log(file, response);
        $modal.modal("show");
    },
    completemultiple: function (file, response) {
        console.log(file, response, "completemultiple");
        //$modal.modal("show");
    },
    reset: function () {
        console.log("resetFiles");
        this.removeAllFiles(true);
    }
});

where


autoProcessQueue: false

this disables automatic image upload when user selects an image, Where we are uploading images, when user submits (or click on the button) the form along with form fields data.


uploadMultiple: true

By default DropZone.js uploads only single image at a time, if set uploadMultiple: true it enables multiple image uploads.


url: 'ajax.php',
maxFiles: 3,

It's mandatory to specify image upload URL, also we specified maxFiles count so that restricting maxFiles upload at a time only 3.

Step 4: Handling Image Upload Using PHP:

I have written simple PHP script which handles image upload on the server side. Whenever you post images, it will get and restructure and uploads that's to the server.


<?php

/**
 * PHP Image uploader Script
 */
$uploaddir = './uploader/';

$images = restructureArray($_FILES);
//echo '<pre>';print_r($images);echo '</pre>';exit;

$data = [];

foreach ($images as $key => $image) {
    $name = $image['name'];
    $uploadfile = $uploaddir . basename($name);
    if (move_uploaded_file($image['tmp_name'], $uploadfile)) {
        $data[$key]['success'] = true;
        $data[$key]['src'] = $name;

    } else {
        $data[$key]['success'] = false;
        $data[$key]['src'] = $name;
    }
}   

echo json_encode($data);exit;

/**
 * RestructureArray method
 * 
 * @param array $images array of images
 * 
 * @return array $result array of images
 */
function restructureArray(array $images)
{
    $result = array();
    foreach ($images as $key => $value) {
        foreach ($value as $k => $val) {
            for ($i = 0; $i < count($val); $i++) {
                $result[$i][$k] = $val[$i];
            }
        }
    }

    return $result;
}

Step 5: Save User Info and Images Details Using PHP and MySQL:

I have written PHP script which inserts user information and images details their uploaded in the database. Here is the SQL query for tables. Please download the full script which I have written more structured way i think.



--
-- Database: `dropzone`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `name` varchar(75) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(75) COLLATE utf8_unicode_ci NOT NULL,
  `mobile` varchar(20) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_images`
--

CREATE TABLE IF NOT EXISTS `user_images` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `image` varchar(150) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `user_images`
--
ALTER TABLE `user_images`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user_images`
--
ALTER TABLE `user_images`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!