Dropzonejs cannot submit properly - javascript

Here is my dropzone config:
var myDropzone = new Dropzone(".myDZ", {
url: $('#form').attr('action'),
previewTemplate: previewTemplate,
uploadMultiple: true,
previewsContainer: "#previews",
clickable: "#fileinput-btn",
autoProcessQueue: false,
init: function() {
var dz = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
e.preventDefault();
dz.processQueue();
});
}
});
After the submit button is pressed, I can see from the backend that the data was submitted correctly. However, after the backend returns a response, the front end will not react to it. The form page stays the same without displaying the returned message and clicking on the submit button again will not trigger any submit.
I tried this:
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
e.preventDefault();
dz.processQueue();
document.getElementById("form").submit();
});
}
});
This will force the form to submit twice but display the correct response after the 2nd attempt. This works but feels wrong.
Any suggestions on what might went wrong?

I would agree that submitting it twice is kind of dirty.
You might try to catch your response in a success function because Dropzone is waiting asynchronously.
var myDropzone = new Dropzone(".myDZ", {
url: $('#form').attr('action'),
previewTemplate: previewTemplate,
uploadMultiple: true,
previewsContainer: "#previews",
clickable: "#fileinput-btn",
autoProcessQueue: false,
init: function() {
var dz = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
e.preventDefault();
dz.processQueue();
});
},
// Try this success.
success: function (data, response) {
console.log(response);
}
});

Related

Dropzone JS not working with multiple input Laravel

i have multiple input, textarea and select i need multiple image upload so i try dropzone js and in controller request there is no file
i use autoProcessQueue: false and its not working but if i don't use it upload but i don't get data in request file
Problem is how can i get request file from dropzone
this is dropzone script
<script>
Dropzone.options.dropzone =
{
// The configuration we've talked about above
url: "{{ route('product.store') }}",
headers: {
'x-csrf-token': "{{ csrf_token() }}",
},
// autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
// The setting up of the dropzone
init: function() {
var myDropzone = this;
var formData = new FormData();
// First change the button to actually tell Dropzone to process the queue.
$("#prodcutCreate").click(function (e){
// Make sure that the form isn't actually being sent.
var formData = new FormData(this);
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.
// formData.append("name", $("#name").val());
// formData.append("slug", $("#slug").val());
// formData.append("description", $("#description").val());
// formData.append("ideal_for", $("#ideal_for").val());
// formData.append("main_ingredients", $("#main_ingredients").val());
// formData.append("gender_id", $("#gender_id").val());
// formData.append("brand_id", $("#brand_id").val());
// formData.append("categories", $("#categories").val());
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
console.log('success');
console.log(files);
console.log(response);
});
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
console.log(false);
console.log(files);
console.log(response);
});
}
}
this is controller i dd the request but no file
public function store(Request $request){dd($request); }
this is form i have other input fileds too
<form method="POST" action="{{ route('product.store') }}" enctype="multipart/form-data">
<div class="col-span-4 dropzone" id="dropzone"></div>
this is from $request
files: Symfony\Component\HttpFoundation\FileBag
{#46
#parameters: []
}
thanks

Dropzone Success function not working

I am trying to implement Bootstrap Dropzone on a website but I am facing a problem getting the success message. Below is my code.
var mydropzone = new Dropzone("#dropzonejs-example", {
url: "/Home/FilesUpload/",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
addRemoveLinks: true,
init: function() {
this.on("sending", function(file, xhr, formData) {
formData.append("is_visible", $('#is_visible').is(':checked'));
this.removeFile(file);
this.on("success", function(fname) {
console.log("ok");
});
});
},
});
$("#uploadbtn").click(function() {
mydropzone.processQueue();
});
My controller returns a string so I want to catch the string here. How can it be possible or where am I doing the mistake? Please correct my code.

Dropzone.js 5.0 - use existing images and send the data to the server

I have successfully used Dropzone to display existing files from my server. However, when I submit the form, only new files are submitted to the server, so I don't know if the user has deleted any. Essentiall I want to send the data for all the files currently displayed, including the 'mocked' files and the newly uploaded ones.
I am using autoProcessQueue: false so that I can have a separate submit button to send the data to the server.
My Code:
Dropzone.options.createListingForm = {
autoProcessQueue: false,
uploadMultiple: true,
previewsContainer: '.create-listing-form-uploads',
parallelUploads: 100,
maxFiles: 100,
addRemoveLinks: true,
init: function () {
var thisDropzone = this;
var photos = form.data('photos');
$.each(photos, function (key, photo) {
var mockFile = {
name: photo.name,
size: photo.size,
type: photo.type,
accepted: true
};
thisDropzone.files.push(mockFile); // add to files array
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, photo.path);
thisDropzone.emit("complete", mockFile);
});
}
};
form.on('click', '.create-listing-form-save-photos', function () {
$('.dropzone').get(0).dropzone.processQueue();
return false;
});
Thanks to this answer for the first part of my code:
https://stackoverflow.com/a/45701181/5482719
Each time a file (including mock Files) is removed/deleted from the dropzone, the removedfile event is fired.
You could use this event to delete the removed file from your server as follows:
myDropzone.on("removedfile", function(file) {
// 'file' parameter contains the file object.
console.log('Removed File', file);
// Delete file from server
$.ajax({
type: 'POST',
url: 'url/that/handles/delete',
data: {
fileName: file.name,
},
dataType: 'json'
}).done(function (response) {
// check repsonse, notify user
}).fail(function(resp) {
console.log('xhr failed', resp);
}).always(function(resp) {
// do nothing for now
});
});
Hope that helps.

Dropzone, how to not process queue if errors exist

So I have a form with Dropzone, plus another textarea, which I want to submit - if I insert an oversize file or too many I get the "oversize" error in the preview container, etc. BUT the form continues to process upon button clicking the form submit (due to my listener). How can I only submit if there file size is correct for both files and doesn't exceed max file limit? I can't see a Dropzone event for say "no errors" to add a click event listener - I think I'm close but semi stuck now, I have the below:
$(function() {
var minImageWidth = 300, minImageHeight = 300;
Dropzone.options.jobApplicationUpload = {
autoProcessQueue: false,
addRemoveLinks: true,
uploadMultiple: true,
paramName: 'file',
previewsContainer: '.dropzone-previews',
acceptedFiles: '.pdf, .doc, .docx',
maxFiles: 2,
maxFilesize: 2, // MB
dictDefaultMessage: '',
clickable: '.fileinput-button',
accept: function(file, done) {
done();
},
// 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.
if(myDropzone.files.length > 0) {
$('#job-application-container').hide();
$('#spinner-modal').modal('show');
$('#spinner-modal p').html('<b>Sending your application,</b> please wait...</p>');
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
}
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
$('#job-application-container').hide();
console.log('okay' + response);
localStorage['success'] = 'test';
location.reload();
});
}
};
});
If you want to verify dropzone errors, you can check the rejected files that it contains.
A simple example (with restricted for only one file, maxfilesize to 1Mb and use version 4.3.0):
var myDropzone = new Dropzone("div#myDropzone", {
url: "toLoadUrl",
autoProcessQueue: false,
uploadMultiple: false,
maxFiles: 1,
maxFilesize: 1,
init: function() {
this.on("addedfile", function() {
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
}
});
$('#toServerButton').on('click',function(e){
e.preventDefault();
if (myDropzone.files.length == 0){
alert("You should be select any file");
} else if(myDropzone.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
myDropzone.processQueue();
}
});
I hope that it was useful to you.
Regards, Yecid

DropZone - How to cancel uploading and remove from queue the correct way

I need to alert the user if he's uploading and existing (on the server) file; i've done it on accept function, like this:
var myDropzone = new Dropzone("form#allegati", {
acceptedFiles: "image/*,.docx,application/pdf",
url: "allegati.php", // Set the url,
dictRemoveFileConfirmation: "Sei sicuro?",
maxFilesize: 10,
thumbnailWidth: 80,
thumbnailHeight: null,
parallelUploads: 20,
createImageThumbnails: true,
previewTemplate: previewTemplate,
autoQueue: true, // Make sure the files aren't queued until manually added
previewsContainer: "#previews", // Define the container to display the previews
clickable: ".fileinput-button", // Define the element that should be used as click trigger to select files.
accept: function (file, done) {
var idIncarico = GetURLParameter('idIncarico');
$.ajax({
// AJAX POST TO CHECK IF FILE EXISTS ON THE SERVER (RETURN TRUE/FALSE)
type: 'POST',
url: 'allegati.php?checkExisting=true&id='+idIncarico,
data: { fileName: file.name },
async: false,
dataType: 'json',
success: function(data) {
// ASKS THE USER TO OVERWRITE
if (data) {
var q = confirm("File esistente. Vuoi sovrascrivere?");
if (q == false){
// IF USER CANCEL UPLOAD:
done("no");
} else {
// IF USER CONFIRM UPLOAD:
done();
}
} else {
done();
}
}
});
},
init: function() {
this.on("error", function(file){
// I GET HERE WHEN USER CLICK ON "CANCEL"
console.log(myDropzone);
});
[CUTTED]
Every seems to work except when the user cancel the upload: the queued file stays there.
I should not call removeFile(file) because I have an ajax script, also bound to every single file "delete" button, that removes existing file from the server (because of the same filename)...
Is there a way to remove the rejected one without calling removeFile(file)?
Screenshot attached
Alex

Categories