multiple dropzone causes only first added dropzone to pick up files added to second dropzone - dropzone.js

This is how I initiate them:
var myDropzone = new Dropzone("#galleryUploadDropzone", Dropzone.options.myAwesomeDropzone)
var myDropzone = new Dropzone("#galleryUploadDropzone2", Dropzone.options.myAwesomeDropzone2)
Dropzone.options.myAwesomeDropzone and Dropzone.options.myAwesomeDropzone2 are used to initiate them.
Both dropzone initiate correctly with no errors, however when I upload something in the second dropzone upload of it gets displayed in the first dropzone and not the second.
this is how options objects look:
Dropzone.options.myAwesomeDropzone = {
// Dropzone configuration
autoProcessQueue: true,
addRemoveLinks: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 20,
previewsContainer: '#dropzone-previews',
// clickable:'#dropzone-previews',
acceptedFiles: ".jpeg,.jpg,.png,.gif,.bmp",
maxFilesize: 2,
// The setting up of the dropzone
init: function() {
myDropzone = this;
myDropzone.on("addedfile", function(file) {
$( '#uploadMsg' ).hide();
});
myDropzone.on("maxfilesexceeded", function(file) {
$( '#uploadMsg' ).append('<h4>Max amount of files exceeded. Only '+maxFiles+' files can be uploaded at once.</h4>');
});
// First change the button to actually tell Dropzone to process the queue.
$("#sbmtbtn").on('click',function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
console.log('sendingmultiple')
});
this.on("successmultiple", function(files, response) {
console.log('successmultiple')
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
setTimeout(removeFiles, 500)
console.log('removeFiles should be called soon')
freshLibraryImages = response.images
});
this.on("errormultiple", function(files, response) {
// alert('error');
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
and the second
Dropzone.options.myAwesomeDropzone2 = {
// Dropzone configuration
autoProcessQueue: true,
addRemoveLinks: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 20,
previewsContainer: '#dropzone-previews',
// clickable:'#dropzone-previews',
acceptedFiles: ".jpeg,.jpg,.png,.gif,.bmp",
maxFilesize: 2,
// The setting up of the dropzone
init: function() {
myDropzone2 = this;
myDropzone2.on("addedfile", function(file) {
$( '#uploadMsg' ).hide();
});
myDropzone2.on("maxfilesexceeded", function(file) {
$( '#uploadMsg' ).append('<h4>Max amount of files exceeded. Only '+maxFiles+' files can be uploaded at once.</h4>');
});
// First change the button to actually tell Dropzone to process the queue.
$("#sbmtbtn").on('click',function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone2.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
console.log('sendingmultiple')
});
this.on("successmultiple", function(files, response) {
console.log('successmultiple')
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
setTimeout(removeFiles, 500)
console.log('removeFiles should be called soon')
freshLibraryImages = response.images
});
this.on("errormultiple", function(files, response) {
// alert('error');
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
what am I doing wrong here?

Instantiate the second dropzone to a different variable
var myDropzoneA = new ...
var myDropzoneB = new ...
and refer to them as such

Related

PWA doesn't execute jQuery form on success event every time

I have a working installable PWA. Here's my service worker's fetch code:
self.addEventListener('fetch', async e => {
e.respondWith(
fetch(e.request)
.catch(error => {
console.log(error);
return caches.match(e.request) ;
})
);
});
In another JS file I have form handling logic (this file also registers the service worker):
$("#myForm").submit(function (e) {
console.log("form submit");
let url = $(this).attr("action");
let method = $(this).attr("method");
let data = $(this).serialize();
$.ajax({
type: method,
url: url,
data: data,
success: function (response) {
console.log("SUCCESS");
},
error: function(err) {
console.log(err);
}
});
});
The problem is that sometimes the form callback is not triggered, but the form submission is triggered every time (based on the "form submit" in console).
I think figured it out. I forgot to disable the generic form submission event.
I added this in the event handling:
e.preventDefault();

Change clickable property on dropzone dynamically

I'm using dropzone for single upload. I would like to disable dropzone while uploading. I tried to set clickable property to false on addedfile event and then set it back to true on success, but dropzone doesn't update with changes. How exactly can I change clickable property dynamically?
Thanks.
I had similar problem, the dropzone itself has disable() and enable(). Try the code below
init: function() {
myDropzone = this;
},
addedfile: function() {
myDropzone.disable()
},
success:function(file, response) {
myDropzone.enable()
....
}
Depends on your needs you can replace
addedfile: function() {
myDropzone.disable()
},
with the code below
sending: function() {
myDropzone.disable()
},

Kendo grid batch edit notifications

I am using a kendo grid with batch editing style.
When editing (or creating) multiple records, the dataSource call update (or create) for each modified record.
Is there a way to get notified when all of these requests are finished?
There's a requestEnd event that is fired when all requests are complete
From their docs:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
}
},
requestEnd: function(e) {
var response = e.response;
var type = e.type;
console.log(type); // displays "read"
console.log(response.length); // displays "77"
}
});
dataSource.fetch();
Note that this fires when all requests are made including initial loads and updates so you might want to check on which type request has completed:
function onGridRequestEnd(e) {
if (e.type === "update") { //whatever... };
}

DropZonejs: Submit form without files

I've successfully integrated dropzone.js inside an existing form. This form posts the attachments and other inputs like checkboxes, etc.
When I submit the form with attachments, all the inputs post properly. However, I want to make it possible for the user to submit the form without any attachments. Dropzone doesn't allow the form submission unless there is an attachment.
Does anybody know how I can override this default behavior and submit the dropzone.js form without any attachments? Thank you!
$( document ).ready(function () {
Dropzone.options.fileUpload = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 50,
maxFiles: 50,
addRemoveLinks: true,
clickable: "#clickable",
previewsContainer: ".dropzone-previews",
acceptedFiles: "image/*,application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.template, application/vnd.openxmlformats-officedocument.presentationml.template, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.presentationml.slide, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.wordprocessingml.template, application/vnd.ms-excel.addin.macroEnabled.12, application/vnd.ms-excel.sheet.binary.macroEnabled.12,text/rtf,text/plain,audio/*,video/*,.csv,.doc,.xls,.ppt,application/vnd.ms-powerpoint,.pptx",
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
window.location.replace(response.redirect);
exit();
});
this.on("errormultiple", function(files, response) {
$("#notifications").before('<div class="alert alert-error" id="alert-error"><button type="button" class="close" data-dismiss="alert">×</button><i class="icon-exclamation-sign"></i> There is a problem with the files being uploaded. Please check the form below.</div>');
exit();
});
}
}
});
Use the following:
$('input[type="submit"]').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
var form = $(this).closest('#dropzone-form');
if (form.valid() == true) {
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([]); //send empty
}
}
});
Reference: https://github.com/enyo/dropzone/issues/418
You should check if there are files in the queue. If the queue is empty call directly dropzone.uploadFile(). This method requires you to pass in a file. As stated on [caniuse][1], the File constructor isn't supported on IE/Edge, so just use Blob API, as File API is based on that.
The formData.append() method used in dropzone.uploadFile() requires you to pass an object which implements the Blob interface. That's the reason why you cannot pass in a normal object.
dropzone version 5.2.0 requires the upload.chunked option
if (this.dropzone.getQueuedFiles().length === 0) {
var blob = new Blob();
blob.upload = { 'chunked': this.dropzone.defaultOptions.chunking };
this.dropzone.uploadFile(blob);
} else {
this.dropzone.processQueue();
}
Depending on your situation you could simply submit the form:
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
$("#my_form").submit();
}
The first approach is kind of too expensive for me, I would not like to dive into the source code and modify it,
If you happen to be like me , use this.
function submitMyFormWithData(url)
{
formData = new FormData();
//formData.append('nameOfInputField', $('input[name="nameOfInputField"]').val() );
$.ajax({
url: url,
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
And in your dropzone script
$("#submit").on("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0)
{
myDropzone.processQueue();
} else {
submitMyFormWithData(ajaxURL);
}
});
I tried Matija Grcic's answer and I got the following error:
Uncaught TypeError: Cannot read property 'name' of undefined
And I didn't want to modify the dropzone source code, so I did the following:
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([{name:'nofiles'}]); //send empty
}
Note: I'm passing an object inside the array to the uploadFiles function.
Then I check server-side, if name != 'nofiles' do upload stuff.
Pretty simple, you stop the propagation ONLY if you have files to be submitted via Dropzone:
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Stop the propagation ONLY if you have files to be submitted via Dropzone
if (myDropzone.getQueuedFiles().length > 0) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
}
});
I have successfully used :
submitButton.addEventListener("click", function () {
if(wrapperThis.files.length){
error = `Please select a file`;
} else {
wrapperThis.processQueue();
}
});
My answer is based on the fact that the other answers don't allow for an Ajax based solution where an actual HTML form isn't actually being used. Additionally you may want the full form contents submitted when sending the Files for upload as well.
As you'll see, my form occurs in a modal outside of any form tag. On completion, the modal is triggered to close.
(FYI getForm returns the form as an object and not directly related to the answer. Also assumes use of jQuery)
init: function() {
var dzClosure = this;
// When saving what are we doing?
$('.saveBtn').off('click').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if (dzClosure.getQueuedFiles().length > 0) {
dzClosure.processQueue();
dzClosure.on('queuecomplete',function(){
$('.modal:visible').modal('hide');
})
} else {
var params = getForm();
$.post(dzClosure.options.url,params,function(){
$('.modal:visible').modal('hide');
})
}
});
dzClosure.on('sending', function (data, xhr, formData) {
var extra = getForm();
for (key in extra){
formData.append(key,extra[key]);
}
});

Adding autoresize to server side generated textarea using jQuery

Am using a plugin called "jQuery Autosize!" on my textareas. How can i make it autoresize my server side generated textareas because they generated when the page has already loaded.
This is the code that generates the server side textareas. resultErrorObj.node_html contains the server side generated textarea as shown below.
$(document).ready(function() {
$("#postUpdate").submit(function(event){
// setup some local variables
var $form = $(this),
// let's select and cache all the fields
$inputs = $form.find("input"),
// serialize the data in the form
serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.attr("disabled", "disabled");
// fire off the request to /form.php
$.ajax({
url: base_url + "ajax/post_status_update",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
var resultErrorObj = jQuery.parseJSON(response);
if (resultErrorObj.status == 1)
{ $(resultErrorObj.node_html).hide().insertAfter('#activitiesStream').slideDown('fast');
}
else
{
alert(resultErrorObj.error);
}
},
// callback handler that will be called on error
error: function(jqXHR, textStatus, errorThrown){
// the error
alert("Error here " + errorThrown);
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
});
Thank you!
The website for Autosize (http://jacklmoore.com/autosize) shows that you can manually trigger the autosizing.

Resources