DropzoneJS & Laravel - Output form validation errors - javascript

I am trying to output form validation errors when you hover over the "X" in the dropped off file in Dropzone.
What I get:
How can I make the object Object output the actual error message from the form validation? I can alert the error message but can't actually show the error message upon hovering over the x.
My js file:
Dropzone.options.fileupload = {
maxFilesize: 20,
init: function () {
thisDropzone = this;
this.on("error", function (file, responseText) {
$.each(responseText, function (index, value) {
alert( value); //this shows the alert of the error message
});
});
}
};
My controller:
$this->validate($request, [
'file' => 'max:20000',
]);

I have fixed my issue.
To anyone who might have the same issue.
I fixed it by simply putting $('.dz-error-message').text(value);
Full code:
Dropzone.options.fileupload = {
maxFilesize: 50,
init: function () {
thisDropzone = this;
this.on("error", function (file, responseText) {
$.each(responseText, function (index, value) {
$('.dz-error-message').text(value);
});
});
}
};

If you want just laravel validation errors use that.
...
init: function () {
thisDropzone = this;
this.on("error", function (file, responseText) {
$.each(responseText, function (index, value) {
if (index === 'errors'){
$('.dz-error-message').text(value.file);
}
});
});
},
...
Or if you just want dropzone.js error outputs change.
if(index === message)

Related

How to add a process bar when you waiting for a response from the server

could someone help me with one problem? I want to add a process bar when you waiting for a response from the server (Django 3.x).
Step to reproduce:
On the page 'A' we have the form.
Enter data to form.
Submit POST request by clicking to button on the page 'A'.
Waiting for getting the result on the page 'A'.
Get the result on the page 'A'.
So, I want to add process bar after 4th and before 5th points on the page 'A'. When you will get the result on the page 'A' it should disappear.
Python 3.7
Django 3.x
You can use nprogress, it's a library used for progress bars. Use this inside the interceptor where you can config it for displaying only when request is in progress until finished.
There are lots of ways to do this. I think using jquery would be easier. Basically you just need to prevent submitting the page and do an Ajax request to server. something like
<script type='text/javascript'>
$(document).ready(function () {
$("form").submit(function (e) {
// prevent page loading
e.preventDefault(e);
$('#loadinAnimation').show();
// preapre formdata
$.ajax({
type: "yourRequestType",
url: "yourUrlEndpoint",
data: formdata,
success: function (data) {
$('#loadinAnimation').hide();
// do rest of the work with data
}
});
});
});
</script>
and show appropriate loading animation in your html part
<div id='loadinAnimation' style='display:none'>
<div>loading gif</div>
</div>
You can also do it using UiKit Library in Javascript on your Django Template Page.
Below code is when a file is Uploaded
In your template file (template.html)
<body>
..
<form>
<progress id="js-progressbar" class="uk-progress" value="0" max="100" hidden></progress>
...
<div class="uk-alert-danger uk-margin-top uk-hidden" id="upload_error" uk-alert></div>
...
</form>
</head>
<script type="text/javascript">
$(document).ready(function(){
var bar = document.getElementById('js-progressbar');
UIkit.upload('.js-upload-list', {
url: '',
name : "customer-docs",
params :{
"csrfmiddlewaretoken":"{{csrf_token}}"
},
method : "POST",
concurrent:1,
allow:'*.(csv|xlsx)',
beforeSend: function (environment) {
console.log('beforeSend', arguments);
// The environment object can still be modified here.
// var {data, method, headers, xhr, responseType} = environment;
},
beforeAll: function (args,files) {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function (files) {
console.log("---------------")
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (data) {
console.log('completeAll', arguments);
console.log('completeAll', data);
let redirect_loc = ""
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
// This is the response from your POST method of views.py
data.responseText = JSON.parse(data.responseText)
if(data.responseText.status == 201){
// swal is another library to show sweet alert pop ups
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Done: true
},
}).then((value) => {
switch (value) {
case "Done":
window.location.href = ""
break;
}
});
}
else if(data.responseText.status == 500){
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Ok: true
},
}).then((value) => {
switch (value) {
case "Ok":
window.location.href = ""
break;
}
});
}
}
});
// This block of code is to restrict user to upload only specific FILE formats (below example is for CSV & XLSX files)
(function() {
var _old_alert = window.alert;
window.alert = function(e) {
console.log(e)
if(e.includes("csv|xlsx") || e.includes("Invalid file type")) {
$("#upload_error").html("Invalid file format. Valid formats are CSV, XLSX").removeClass('uk-hidden')
}else if(e.includes("Internal Server Error")) {
$("#upload_error").html("Internal Server Error Kindly upload Documents again").removeClass('uk-hidden')
}
else {
_old_alert.apply(window,arguments);
$("#upload_error").addClass('uk-hidden').html("")
}
};
})();
});
</script>
On your views.py you can do your computation and once done, you can return a response like below
resp_json = {
"status" : 201,
"status_icon" : "success",
"url" : "/",
"message": message
}
return HttpResponse(json.dumps(resp_json))
For more info on SWAL (Sweet Alerts), visit https://sweetalert.js.org/guides/

Reveal module pattern - can't find the method

I am using reveal module pattern but can't call the method.
$(function () {
$(document).on("click", '.EditBill', function () {
editModule.EditBill(this);
});
});
var editModule = (function () {
function EditBill(object) {
var itemId = $(object).data('itemid');
loader.show();
$.ajax({
url: 'Bill/Edit',
data: { id: ItemId },
success: function (data) {
loader.hide();
$('#ModelPopup').empty();
$('#ModelPopup').html(data);
$(function () {
$('#editModal').modal();
});
}
});
}
return
{
EditBill: EditBill
}
}());
When I debug in Edge, I click the button ('.EditBill'), the message is
> SCRIPT5007: Unable to get property 'EditBill' of undefined or null
Thanks for Shyju, the answer is return and the first curly brace '{', should be on the same line! It works now. I don't understand why I have to follow this syntas, but it works.

Remove all files dropzoneJs only image upload

How I can remove images after sendingmultiple without removing other params? I tried this but it does not work:
init: function () {
this.on('sendingmultiple', function(file, xhr, formData){
formData.append('ids', $("#ids").val());
});
},
init: function () {
this.on("completemultiple", function (file) {
this.removeAllFiles();
});
},
I do not want to delete this id, just images
In drop zone above the following function use
function isImage($img){
return (bool)getimagesize($img);
}
if(isImage($_FILES['file']['tmp_name'])){
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))

Handling FilePathResult return values using filedownload jquery plugin

I am using fileDownload jQuery plugin to download a file which is served using ASP.NET MVC. The action is decorated with HttpGet and returns a FilePathResult. It works when a file is found. If a file is not found, I am not sure what to return in the action?
JavaScript:
function showMessageCancelDialog(message, request, titleValue) {
'use strict';
$('#messageDialog').html(message);
$('#messageDialog').dialog({
resizable: false,
width: '320px',
modal: true,
title: titleValue,
dialogClass: 'no-close',
buttons: {
Cancel: function () {
request.abort();
$(this).dialog("close");
}
}
});
}
function hideMessageDialog() {
'use strict';
$('#messageDialog').dialog("close");
}
function DownloadAttachment(itemId) {
'use strict';
var getAttachmentFileUrl = "/App/Download/GetAttachmentFile?ItemId=" + itemId;
var ajaxRequest = $.fileDownload(getAttachmentFileUrl, {
successCallback: function (message) {
hideMessageDialog();
},
failCallback: function (errorMessage) {
hideMessageDialog();
showMessageDialog("Download request failed:" + errorMessage, "Download attachment");
}
});
showMessageCancelDialog("Download in progress... , ajaxRequest, "Download attachment");
}
ASP.NET:
if(errorMessage == string.Empty)
{
this.Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadFile);
return new FilePathResult(downloadFile, "application/octet-stream");
}
else
{
// WHAT DO I RETURN HERE?
}
You could throw an error with your errorMessage and the jquery function failCallback() should catch that.
else {
throw new HttpException(404, errorMessage);
}
this.Response.Clear();
this.Response.StatusCode = 500;
this.Response.ContentType = "text/html";
this.Response.Write(errorMessage);
throw new Exception(errorMessage);
The above code called the failCallback on javascript

Integrating Dropzone.js with angular

I am working from some code that integrated DropboxJS as an angular directive. I cannot get it to work. I've taken his fiddle and updated it with current CDN links. Any idea why the directive code never fires? For ex if I drop an image it will go to /upload instead of /desiredupload and the event doesn't fire.
Fiddle: http://jsfiddle.net/cyberwombat/3tDqZ//1/
angular.module('dropZone', [])
.directive('dropZone', function() {
return function(scope, element, attrs) {
element.dropzone({
url: "/desiredupload",
maxFilesize: 100,
paramName: "uploadfile",
maxThumbnailFilesize: 5,
init: function() {
this.on("addedfile", function(file) {
alert("Added file."); });
}
});
}
});
angular.module('dropZone', [])
.controller('dropZoneCtrl', function() {});
Additionally and unfortunately I cannot replicate in my fiddle - on my local code I get this error: Object [object Object] has no method 'dropzone'
I am loading dropzone, then angular (tried the the other way) then my app, directives, etc.. so I don't think order is an issue. Dropzone successfully detects the form and makes it DnD but my directive element doesn't seem to have dropz
This is how I do it:
.directive('dropZone', function () {
return {
scope: {
action: "#",
autoProcess: "=?",
callBack: "&?",
dataMax: "=?",
mimetypes: "=?",
message: "#?",
},
link: function (scope, element, attrs) {
console.log("Creating dropzone");
// Autoprocess the form
if (scope.autoProcess != null && scope.autoProcess == "false") {
scope.autoProcess = false;
} else {
scope.autoProcess = true;
}
// Max file size
if (scope.dataMax == null) {
scope.dataMax = Dropzone.prototype.defaultOptions.maxFilesize;
} else {
scope.dataMax = parseInt(scope.dataMax);
}
// Message for the uploading
if (scope.message == null) {
scope.message = Dropzone.prototype.defaultOptions.dictDefaultMessage;
}
element.dropzone({
url: scope.action,
maxFilesize: scope.dataMax,
paramName: "file",
acceptedFiles: scope.mimetypes,
maxThumbnailFilesize: scope.dataMax,
dictDefaultMessage: scope.message,
autoProcessQueue: scope.autoProcess,
success: function (file, response) {
if (scope.callBack != null) {
scope.callBack({response: response});
}
}
});
}
}
})
An example usage of this would be:
<div action="/file/upload/" class="dropzone" drop-zone
call-back="myCallBackMethod(response)"
data-max="5"
auto-process="false"
message="Drop file here or click to select"
mimetypes=".doc,.docx,.pages,.pdf,.odt"
id="file-dropzone">
</div>
Any scope variable that has a ? next to it is optional. The only required field is action, which would be the URL to send post to.
$(element).dropzone({
url: "/desiredupload",
maxFilesize: 100,
paramName: "uploadfile",
maxThumbnailFilesize: 5,
init: function() {
this.on("addedfile", function(file) {
alert("Added file."); });
}
});
Wrap element with $(...). In AngularJS it says all DOM elements are JQuery object but I think you might be using a older version of AngularJS.

Categories