DropzoneJS Event Listener won't loaded - javascript

I have followed the usage examples from the DropzoneJS documentation and some other from stackoverflow. However, I still can't make it work. Here is my Dropzone Code.
<p class="h6 my-0 mb-10">PEMERIKSAAN</p>
<form action="{{url('radiologi/upload/gambar')}}" class="dropzone" id="my-dropzone" method="POST">
<input type="hidden" name="saltPict" value="{{$key}}">
<input type="hidden" name="target" value="{{$transaksi->slug}}">
{{csrf_field()}}
</form>
And here, the javascript code that I've added to catch the event which isn't worked.
<script type="text/javascript">
Dropzone.autoDiscover = false;
Dropzone.options.myDropzone = {
init: function() {
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
$("#submit-all").removeAttr("disabled");
}
});
this.on("processing", function (file) {
console.log("check");
$("#submit-all").attr("disabled", "disabled");
});
}
};
// $("#my-dropzone").dropzone();
Dropzone.options.myDropzone.init();
</script>
I've try to place the javascript code either inside the document ready function or not. Still, it doesn't work. The only error output is this
My only purpose is to catch the event when DropzoneJS has done uploading all of my files.

Wow, It's worked like magic. I just try one more example from the Dropzone documentation. Surprisingly, the code are simpler.
Dropzone.autoDiscover = false;
$(function() {
// Now that the DOM is fully loaded, create the dropzone, and setup the
// event listeners
var myDropzone = new Dropzone("#my-dropzone");
myDropzone.on("complete", function(file) {
console.log("halo");
/* Maybe display some more file information on your page */
});
})
And don't place this on $(document).ready function so it will be called before the Dropzone itself are attached. Thanks for anyone who has tried to help me.

You should't call myDropzone.init by your self, dropzone will do it for you.

Dropzone triggers events when processing files, to which you can register easily, by calling .on(eventName, callbackFunction) on your instance.
Since listening to events can only be done on instances of Dropzone, the best place to setup your event listeners, is in the init function:
// The recommended way from within the init configuration:
Dropzone.options.myAwesomeDropzone = {
init: function() {
this.on("addedfile", function(file) { alert("Added file."); });
}
};

Related

Can't explicitly render Google ReCaptcha and have a callback function working

I am building a form on a website, and I am having and issue getting a function to run when the ReCaptcha is submitted. This function removes the disabled attribute on the submit button.
There is also a chance that multiple forms may be used on one page so I implemented the following solution to allow multiple captacha forms on one page:
https://stackoverflow.com/a/33535769/2506219
It seems I can either allow multiple ReCaptcha forms or have the submit button allowed but not both.
Here is the code:
HTML
<div class="g-recaptcha" data-callback="verifyCallback"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
JavaScript
<script>
var CaptchaCallback = function() {
$('.g-recaptcha')
.each(function(index, el) {
grecaptcha.render(el, { 'sitekey': 'XXXX' });
});
};
function verifyCallback() {;
$('#submitBtn').prop('disabled', false);
}
</script>
Thank-you.
Worked it out!
I needed to call the function from the callback, having it in the HTML doesn't work
var CaptchaCallback = function() {
$('.g-recaptcha')
.each(function(index, el) {
grecaptcha.render(el, { 'sitekey': 'XXXX', 'callback': verifyCallback });
});
};

dynamically extend jQuery plugin

i want to create a flexible jquery plugin for handling forms, here's my markup + code:
<div id="myform" validate="1">form</div>
<script>
(function ($) {
$.fn.myForm = function()
{
var me = this;
if(me.attr("validate"))
{
me.validate();
}
};
})(jQuery);
// code from external file eg. myform_validate.js
$.fn.myplugin.validate = function () {
// form validation here
alert("validate");
};
$(document).ready(function(){
$('#myform').myForm();
});
</script>
what i want to achieve is somekind of plugin-in-plugin structure which means myForm is the base plugin for each project and if required i would add extra functionality/methods like form validation or an image uploader to the plugin (by loading additional external scripts).
this should be dont without instantiation, directly inside the plugin.
as you might expect, the above code doesn't work .. :/
any ideas if this is possible?
thanks
There are probably numerous ways to achieve expected results. Here, checks if validate method from "external file" is defined, if yes, sets validate as property of myForm ; utilizes Function.prototype.call to set this within validate
(function($) {
function myForm() {
me = this;
if (me.attr("validate")) {
if (myForm.validate) {
myForm.validate.call(me)
.text(me.text() + " validated")
.css("color", "green");
}
};
return me
};
try {
if (validate && typeof validate === "function") {
myForm.validate = validate
}
// catch `ReferenceError` if `validate` is not defined
} catch (e) {
alert(e.message)
}
$.fn.myForm = myForm;
})(jQuery);
// code from external file eg. myform_validate.js
$(document).ready(function() {
$("#myform").myForm();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
// external file
function validates() {
// form validation here
console.log(this)
alert("validate");
// `this` : `#myform`
return this
};
</script>
<div id="myform" validate="1">form</div>

flipping between register and login form

<script>
$(document).ready(function(){
$("#register_link").click(function()
{
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php");
});
$("#login_link").click(function()
{
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php");
});
});
</script>
This is my jquery code for flipping between login and register forms.
Initially the page contains the login form and a link to load the register form. It works the first time to load the register form and a link to load the login form. But it doesn't work after that. It doesn't change from register to login form. How to rectify this?
This is because the listeners are only set on existing elements. When you load something using Ajax (jQuery.load()), there will be no listeners on those new elements. You can fix it by re-initializing the click listeners, after the new content is loaded, like this:
<script>
function listenToClick() {
$("#register_link").click(function() {
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php", function() {
listenToClick();
});
});
$("#login_link").click(function() {
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php", function() {
listenToClick();
});
});
}
$(document).ready(function(){
listenToClick();
});
</script>
An even better option would be to listen to the click event using the on function. The on function also listens to future elements (the elements created by jQuery.load()).
<script>
$(document).ready(function() {
$("#register_link").on('click', function() {
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php");
});
$("#login_link").on('click', function() {
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php");
});
});
</script>
You can use .on() to delegate the events like this:
$(document).ready(function(){
$(document).on('click', "#register_link, #login_link", function() {
$("#login_or_register")
.empty()
.load($(this).is('#register_link') ? "register_form.php" : "login_form.php");
});
});
Use event delegation to account for elements that don't exist at run time that may be added to the dom later:
$(document).on('click', '#register_link, #login_link').click(function () {
var url = $(this).is('#login_link') ? "login_form.php" :"register_form.php" ;
$("#login_or_register").empty().load(url);
});

How to get the Dropzone.js return value?

I just implemented Dropzone.js to make file uploads on my website easier. The file uploads fine, and after it finished uploading I give the file an id and return this id to the browser.
This works fine, except for that I don't know how to catch the id that gets returned from the server. In this SO answer I found some code that should supposedly do that, but it doesn't work for me. The code I have now is pasted below.
Does anybody know how I can get the value that is returned by the server? All tips are welcome!
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="/static/js/external/dropzone.min.js"></script>
<link href="/static/css/external/dropzone.css" rel="stylesheet">
<script type="text/javascript">
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
console.log('WE NEVER REACH THIS POINT.');
alert(response);
}
};
});
</script>
</head>
<body>
<form action="/doc"
class="dropzone"
id="my-awesome-dropzone"></form>
</body>
</html>
Looking at the source code of dropzone.js, it seems that there is a lot of events you can listen to.
events: [
"drop"
"dragstart"
"dragend"
"dragenter"
"dragover"
"dragleave"
"addedfile"
"removedfile"
"thumbnail"
"error"
"errormultiple"
"processing"
"processingmultiple"
"uploadprogress"
"totaluploadprogress"
"sending"
"sendingmultiple"
"success"
"successmultiple"
"canceled"
"canceledmultiple"
"complete"
"completemultiple"
"reset"
"maxfilesexceeded"
"maxfilesreached"
]
Here the "success" event seems to be appropriate.
A good starting point would be to bind an event listener to your dropzone and see what data you get on such event.
$('#my-awesome-dropzone').on('success', function() {
var args = Array.prototype.slice.call(arguments);
// Look at the output in you browser console, if there is something interesting
console.log(args);
});
$("#dropzoneForm").dropzone({
maxFiles: 2000,
url: "../Uploader/HttpUploadHandler.ashx?param=" + result.prjID,
success: function(file, response){
//alert("Test1");
}
});
Does this help?
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
this.on("success", function(file, responseText) {
var responseText = file.id // or however you would point to your assigned file ID here;
console.log(responseText); // console should show the ID you pointed to
// do stuff with file.id ...
});
}
};
For example, I have mine set up to attach the server path to the image name and pass this as a value into a form field on submit. As long as you define responseText to point to the file ID you should get a return on this.
This link might be helpful as well: https://github.com/enyo/dropzone/issues/244
Try this:
Dropzone.options.myAwesomeDropzone = {
success: function(file, response){
//alert(response);
console.log(response);
}
};
It works for me
$(function() {
var myDropzone = new Dropzone(".dropzone");
myDropzone.on("success", function() {
alert('Uploaded!');
});
});
I am using jQuery and this is what worked for me:
var dz = $(".my-awesome-dropzone").dropzone()[0];
dz.dropzone.on("success", function (file, response) { ... }));
Note that the dropzone() method adds an dropzone attribute to the DOM object. You have to call on() on that object - not the jQuery on().
I wanted to add this as a comment, but I can't, since I have a low reputation.
For those of you who still have trouble retrieving the response from the server, if you're using chunking, Dropzone is hard-coding a blank response in this situation:
https://github.com/enyo/dropzone/blob/caf200c13fd3608dd6bed122926d5848927f55b4/dist/dropzone.js#L2344
if (allFinished) {
_this14.options.chunksUploaded(file, function () {
_this14._finished(files, '', null);
});
}
So retrieving the response doesn't seem to be supported for chunked uploads.

attach 2 functions in form with jquery

I have this html form
<form action="upload/" id="upload" name="upload">
// other form data
</form>
and this in html on page where i can switch form attributes
Download
Upload
and my javascript
$("#startUpload").click(function( {
$("form").attr('action','upload/').attr('id','upload');
});
$("#startDownload").click(function( {
$("form").attr('action','download/').attr('id','download');
});
$(function() {
$('#upload').uploadThis({
// other code here
});
$(function() {
$('#download').downloadThis({
// other code here
});
my problem is when i click on href #startUpload this is attached with $('#upload').uploadThis({}) function and it works but when i click on #startDownload it is not attaching this $('#upload').downloadThis({}) function and not getting called.
thanks for any help.
I'm not sure exactly what is the wanted behavior but changing IDs of elements always brings the same sort of issues.
You are doing this:
$(function() {
$('#upload').uploadThis({
// other code here
});
});
$(function() {
$('#download').downloadThis({
// other code here
});
});
$(<Function>); is a shorthand for $(document).ready(<Function>);
The thing is that when you're document is ready, it will execute both your handlers above but at that time, only an element with ID #upload exists, $('#download') will actually be an empty selection.
What you could do is call $('#upload').uploadThis() and $('#download').downloadThis() in your respective .click() handlers after changing the IDs.
$("#startUpload").click(function( {
$("form")
.attr({ 'action': 'upload/', 'id': 'upload' })
.uploadThis(...);
});
Note: if those are plugins you wrote yourself, be sure that they won't initialize each time you call them.
Hope I'm clear enough :o)
You can do this as many times as you like:
$("#startDownload").bind('click', function() {
...
});
You are trying to bind elements before they exist on DOM... will never work.
$("#startUpload").click(function( {
$("form").attr('action','upload/').attr('id','upload').submit(function() {
$(this).uploadThis({
//other code here
});
);
});
$("#startDownload").click(function( {
$("form").attr('action','download/').attr('id','download').submit(function() {
$(this).downloadThis({
//other code here
});
);
});
THis way you will bind the action you want in the submit form event. Probably will fix your problem.
A simple approach would be to make custom events for the form and trigger them by the onclick's:
$("#startUpload").click(function( {
$("form").trigger('upload');
});
$("#startDownload").click(function( {
$("form").trigger('download');
});
$("form").bind('upload',function(){
$(this).attr('action','upload/').uploadThis();
}).bind('download',function(){
$(this).attr('action','download/').downloadThis();
});

Categories

Resources