i am currently using drop zone to upload files, however, i would like drop zone to append a hidden form input to my main form after it has successfully uploaded the file, for the form to append the filename to my sql database. Therefore, here is the code that i am using:
<script>
Dropzone.options.imageuploaddrop = {
paramName: "fileimage",
maxFilesize: 10, // MB
autoProcessQueue: false,
uploadMultiple: false,
maxFiles: 1,
addRemoveLinks: true,
clickable:true,
acceptedFiles:".jpg,.png,.jpeg,.tif",
dictInvalidFileType:"Invalid File Type. Only Jpg, Png and Tif are supported.",
dictFileTooBig:"File too Big. Maximum 10 MB!",
dictMaxFilesExceeded:"We only need one image.",
init: function() {
var myDropzone = this;
$(function(){
setInterval(oneSecondFunction, 1);
});
function oneSecondFunction() {
if (myDropzone.getAcceptedFiles().length === 0) {
variable2=0;
}else {
variable2=1;
}
}
document.getElementById("submit").addEventListener("click", function(e) {
// First change the button to actually tell Dropzone to process the queue.
if (myDropzone.getQueuedFiles().length == 1) {
// 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('success', function(file, response) {
// If you return JSON as response (with the proper `Content-Type` header
// it will be parsed properly. So lets say you returned:
// `{ "fileName": "my-file-2234.jpg" }`
// Create a hidden input to submit to the server:
***$("#ideaform").append($('<input type="hidden" ' +
'name="files[]" ' +
'value="' + response.fileName + '">'));***
});
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
});
}
}
</script>
As you can see I'm using the success event to append the extra file field, but it seems to me that the file name isn't being appended, although the hidden field is actually being added.
Can anyone suggest why?
Thanks!
I had this issue and solved it as follows:
$("#ideaform").append($('<input type="hidden" ' +
'name="files[]" ' +
'value="' + response['filename'] + '">'));
You can change hidden to text to see the field appear on the page when testing.
Hope that helps someone else!
Related
I am trying to write a delete function in Dropzone.js. In order to do that I need the id of the file the way it was uploaded.
I tried to get a property of an object with no success. Now I am trying to use jQuery to get the value or text content of the span that has it.
this is the screenshot of the structure. The jQuery code I am trying is:
var loooot = $(".dz-filename").parents('span').text();
To be more specific I am trying to get the number 1_1477778745352 (which is a time stamp).
The Dropzone code is as follows:
<script>
var listing_id = "1";
// these are the setting for the image upload
Dropzone.options.pud = {
acceptedFiles: ".jpeg,.jpg,.png,.gif",
uploadMultiple: false,
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
addRemoveLinks: true,
maxFiles: 10,
renameFilename: function (filename) {return listing_id + '_' + new Date().getTime();},
init: function()
{
this.on("removedfile", function(file)
{
var loooot = $("span", ".dz-filename").html();
alert(loooot);
});
}
};
</script>
Try this use JQuery's .text(); to get inner text
Update: use this with DOM .ready() like that.
Deep selector
$(document).ready(function(){
var fname = $("#pud .dz-filename span [data-dz-name]").text();
});
OR (if your form is dynamic)
function get_fname(){
return $("#pud .dz-filename span [data-dz-name]").text();
}
Then use get_fname();
It becomes undefined because dropzone works dynamicly, use this:
$('body').find(".dz-filename").find('span').text();
Best way to do this is to declare dropzone:
//first declare somewhere variable
var my_drop;
// then on creating dropzone:
my_drop = new Dropzone('.dropzone', {
/* your setup of dropzone */
});
Then you can retreive information about files with this:
my_drop.files[0].name
The [0] represent's first file, you can loop through them if there's more then one.
Use:
var loooot = $("span", ".dz-filename").html();
Working Demo.
var loooot = $("span", ".dz-filename").html();
alert(loooot);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dz-filename">
<span>Test</span>
</div>
EDIT
Since you are setting the text dynamically it may happens that jquery read the HTML before that you set it, to prevent this you have to call this function after the timestamp as a callback (i can't help you without seeing how you set the span text).
So do something like:
function setSpan(callback) {
// Set your stuffs
// Call the callback
callback();
}
function getText() {
// I'm the callback witch get the html
}
//Onload
setSpan(getText());
EDIT
For dropzone you can use queuecomplete that start a function after the queue, i'm not an dropzone expert but i suppose:
init: function () {
this.on("queuecomplete", function (file) {
//Get span html
alert("All files have uploaded ");
});
}
The working solution I found is this:
init: function()
{
this.on("removedfile", function(file)
{
var loooot = $(file.previewElement).find('[data-dz-name]').text();
alert(loooot);
});
}
i have an implemented drop zone in my code, however i would like to disable a submit button in a form in my page, when there are no files uploaded onto drop zone, i have the following code:
<script>
// "myAwesomeDropzone" is the camelized version of the HTML element's ID
Dropzone.options.imageuploaddrop = {
paramName: "fileimage",
maxFilesize: 10, // MB
autoProcessQueue: false,
uploadMultiple: false,
maxFiles: 1,
addRemoveLinks: true,
clickable: true,
acceptedFiles: ".jpg,.png,.jpeg,.tif",
dictInvalidFileType: "Invalid File Type. Only Jpg, Png and Tif are supported.",
dictFileTooBig: "File too Big. Maximum 10 MB!",
dictMaxFilesExceeded: "We only need one image.",
init: function () {
this.on("complete", function (file) {
var myDropzone = this;
if (myDropzone.getAcceptedFiles().length = 1) {
myDropzone.processQueue();
} else {
done("There is an Error.");
var submit2 = document.getElementById('submit2');
submit2.disabled = true;
}
});
}
};
</script>
However, it does not work. Anyone can find out why? Thanks! I tried the disable submit code outside and it works it seems like the checking part is not working.
Actually the basis is that i need the javascript code to such that depending on the condition, disable/enable the submit button dynamically (without page refresh). In this case I'm using drop zone, and drop zone doesn't really support multiple elements, so I'm trying to get a workaround in the simplest possible way while validating all form elements at the same time.
Please check camelized version of the HTML element's ID. "imageuploaddrop" is that true?
If only you need a submit button enabled when you upload an image; you can try setting
autoProcessQueue: true
and
init: function () {
var submit2 = document.getElementById('submit2');
submit2.disabled = true;
this.on("complete", function (file) {
submit2.disabled = false;
});
}
I'm using a file uploader called "upload-at-click" from: https://code.google.com/p/upload-at-click/
It works good but the problem I'm having is I need two upload buttons on the page to upload two separate kinds of files. But I can only have one instance of the upclick() function, so I'm not sure how I can do this?
The code used for one button is:
var element = document.createElement('input');
element.value = 'Load CSV';
element.id = 'uploader';
element.type = 'button';
stage.appendChild(element);
upclick({
element: element,
action: '/mailer/file_upload.php',
onstart: function (filename) {
alert('Uploading: ' + filename);
},
oncomplete: function (response_data) {
alert('Data upload complete.');
}
});
I think you can pass element as already existing element from DOM.
$('.uploadButton').click(function(){
upclick({
element : this // or maybe jQuery object $(this) ???
/* rest of code */
});
});
Im using html5 capacities to read image width and height before submitting...
Well, this is not happening exactly, it seems like the time needed for the functions:
reader.readAsDataURL();
reader.onload = function();
image.onload = function();
To read the file is way too much than the time my form is able to wait before sending the pic.
I can check that the beforeSubmit function is triggered, but the form is submitted before it finishes.
Another weird thing is that I have replaced the beforeSubmit function content with a simple return false sentence and the form is being submitted anyway.
Am I missing something regarding the beforeSubmit option in ajaxSubmit?
The beforeSubmit function has been minimized to a return false statement, here comes the submit (the form is inside a dialog(), may be this the clue?:
$('.block .imgpop').on("click",function()
{
type = $(this).attr('emimage');
currentype = type;
options =
{
type: 'POST',
target: '#uploadverbose',
beforeSend: beforeSubmit,
resetForm: true,
success: showResponse,
data: { type: $(this).attr('emimage'), tempname: $(this).attr('id'), maxsize: imgsizesW[$(this).attr('emimage')] },
dataType : "text"
};
$('#uploadbitch').dialog(
{
closeOnEscape: true,
width: 800,
modal: true
});
return false;
});
$(document).on("click","#MyUploadForm input[type=submit]", function(e, submit)
{
if (!submit) e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
$(document).on("submit","#MyUploadForm", function(e, submit)
{
e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
If you try to handle onclick on submit button then it doesn't stop form from submitting.
It may bot be exactly the answer, but it works. I have place all the image testing in the input field with a "change" event and it works just fine for me. Precocity in the form submitting is still unsolved.
I am using the following code to add a button to a page
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
I am then creating an Ajax Upload instance on the button.
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
What I want to do is append the button to the page then simulate clicking it automatically. How would I go about doing this?
Update
The code now reads:
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
$('#fileUpload').click();
The .click event does not seem to fire. It is reached in the code but does nothing...
** Update **
$('#fileUpload').click();
needs to be
$('input').click();
Please check the accepted answer for why.
What I want to do is append the button
to the page then simulate clicking it
automatically. How would I go about
doing this?
The short answer is that you don't.
The long answer:
First you need to understand how AJAX Upload works.
Plugin creates invisible file input on
top of the button you provide, so when
user clicks on your button the normal
file selection window is shown. And
after user selects a file, plugin
submits form that contains file input
to an iframe. So it isn’t true ajax
upload, but brings same user
experience.
There are two things here:
fileUpload is not the actual file input
Generally, <input type="file"> element cannot be clicked/set programmatically in modern browsers for security reasons.
You don't actually have a click handler on the button, hence nothing happens.
Simply by going
$('#fileUpload').click();
You can call the click handler on the button like this:
$('#fileUpload').click();
You have already handled adding it to the page.
$('body').append('Go').find('#send').click();