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 a 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 DropZone.JS Demo
Step 1: Create HTML5 Form and Add Required JS and CSS Files:
In this tutorial, we are going to use following mandatory libraries.
- DropZone.js
- Query
Following are optional libraries that we are using for just styling pages and validating the HTML5 form.
- Bootstrap 4
- jQuery Validation
First, create an 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>
Download Ajax Image Upload Using Dropzone.js Script
Instant Download This 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 Programmatically:
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 the user selects an image, Where we are uploading images when the user submits (or click on the button) the form along with form fields data.
uploadMultiple: true
By default, DropZone.js uploads an only single image at a time, if set
upload multiple: 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 a 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 a PHP script which inserts user information and images details they are uploaded into the database. Here is the SQL query for tables. Please download the full script which I have written the more structured way I think.
Download Ajax Image Upload Using Dropzone.js Script
Instant Download This Script
--
-- 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;
I guess I am the only one who came here to share my very own experience. Guess what!? I am using my laptop for almost the past 2 years, but I had no idea of solving some basic issues. I do not know how to Download Cracked Pro Softwares But thankfully, I recently visited a website named vstfull.com
ReplyDeletedropzone Crack
abbyy-fine-reader Crack
easybits-magic-desktop
I thought this was a pretty interesting read when it comes to this topic. Thank you
ReplyDeleteNsasoft Office Product Key Finder Crack
MacBooster Crack
Dropzone Crack
Minitab Crack
Excellent post, Its really friendly article... good working
ReplyDeleteBandicut Crack
Plugin Alliance Complete Crack
Dropzone Crack