Dropbox uploader Cannot call method 'submit' of undefined - javascript

I have some problems with Dropbox uploader in my Wordpress site.
It gives me 'Uncaught TypeError: Cannot call method 'submit' of undefined' on this lines:
$('#fileupload')
.bind('fileuploadstop', function (e, data) {
//window.location.href = 'http://hiphopsmurf.com';
$('#multimages', top.document).val(upfiles);
parent.document.forms["multi_image"].submit();
//parent.tb_remove();
});
Here is whole document code:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.com') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
process: [
{
action: 'load',
fileTypes: /^image\/(gif|jpeg|png)$/,
maxFileSize: 20000000 // 20MB
},
{
action: 'resize',
maxWidth: 1440,
maxHeight: 900
},
{
action: 'save'
}
]
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<span class="alert alert-error"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
$('#fileupload').fileupload('option', {
//maxFileSize: 5000000,
maxFileSize: 1048576,
//acceptFileTypes: /(\.|\/)(gif|jpe?g|png|psd)$/i,
acceptFileTypes: /(\.|\/)(doc|docx|gif|jpg|jpeg|pdf|png|psd|tif|tiff)$/i,
singleFileUploads: true,
sequentialUploads: true,
autoUpload: true,
});
var upfiles = "";
$('#fileupload')
//.bind('fileuploaddrop', function (e, data) {$.each(data.files, function (index, file) {alert('Added file: ' + file.name);});})
//.bind('fileuploaddrop', function (e, data) {$.each(data.files, function (index, file) { upfiles += file.name + ",";});})
.bind('fileuploaddone', function (e, data) {$.each(data.files, function (index, file) { upfiles += file.name + ",";});})
.bind('fileuploadchange', function (e, data) {/* ... */})
//fail: function (e, data) {data.submit();}
//.fileupload({fail: function (e, data) {alert('FAIL');}});
;
$('#fileupload')
.bind('fileuploadstop', function (e, data) {
//window.location.href = 'http://hiphopsmurf.com';
$('#multimages', top.document).val(upfiles);
parent.document.forms["multi_image"].submit();
//parent.tb_remove();
});
}
});
I'm kind a week in Java script, so will appreciate for any help.

Generally, when working with JavaScript / jQuery when you receive a "method is undefined" error there's an issue with your selector.
I would use a jQuery selector to submit the form. Try replacing the problem line with this:
$('#multi_image').submit();
(That assumes your form has an id attribute of "multi_image").

Related

Multiple File Upload using dropzone and with other forms fields with FormValidation plugin

This is the image of form which I have designed in my project Now my requirement is to upload multiple files and with other form values over a single backend call.
<script>
<form class="form-horizontal" name="addColorForm" id="addColorForm"
enctype="multipart/form-data"
method="POST">
//Colour Name and Code fileds
//Files Uploader Plugin (Dropzone)
<input type="file" name="artworkFiles[]" style="visibility: hidden"/>
</form>
Now my script part
<script>
var validCode = function () { // my custom validation };
FormValidation.validators.validCode = validCode;
FormValidation.formValidation(
document.getElementById('addColorForm'),
{
fields: {
colorName: {
validators: {
notEmpty: {
message: '${message(code:"blank.error.message", default:"This field must be entered")}'
},
}
},
},
plugins: { //Learn more: https://formvalidation.io/guide/plugins
trigger: new FormValidation.plugins.Trigger(),
// Bootstrap Framework Integration
bootstrap: new FormValidation.plugins.Bootstrap(),
// Validate fields when clicking the Submit button
submitButton: new FormValidation.plugins.SubmitButton(),
// Submit the form when all fields are valid
// defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
}
}
).on('core.form.valid', function () {
saveColor();
});
function saveColor() {
var url = "url";
var form = $("#createArtworkForm");
var formData = new FormData(form[0]);
$.ajax({
url: url,
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
success: function (data) {},
cache: false,
contentType: false,
processData: false,
error: function () { }
});
}
var artworkColorsFiles = $('#kt_dropzone').dropzone({
url: "https://www.google.com", // Set the url for your upload script location
paramName: "media", // The name that will be used to transfer the file
maxFiles: 1,
maxFilesize: 40, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
autoProcessQueue: false,
accept: function (file) {
//Logic to add multiple files in an input type hidden which is declared above
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function () {
let content = fileReader.result;
$('#artworkFiles').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
});
</script>
My questions is how to implement this or how should i add my all files(max 3) in a input type file field declared as visibility hidden.
The same I did in my project here is the code hope it will help you.
you have to use the dropzone function to send file and form data in sendingmultiple function you have to add a loop through your formdata enter code here
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
$(document).ready(function () {
zdrop = new Dropzone('#dropzone', {
url: '#Url.Action("SaveOpportunity", "Masters")',
maxFiles: 500,
maxFilesize: 300,
parallelUploads: 100,
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
removeFilePromise: function () {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random() * 3)
console.log(rand);
if (rand == 0) reject('didnt remove properly');
if (rand > 0) resolve();
});
},
sendingmultiple: function (file, xhr, formData) {
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
debugger
$("form#OpportunityForm").find("input[type=file]").each(function (index, field) {
const file = field.files[0];
formData.append('itemfile', file);
});
},
successmultiple: function (file, responseText) {
jQuery('form#OpportunityForm').find('textarea, input').each(function () {
jQuery(this).val('');
});
clear();
swal.fire("Opportunity Details Saved!", "Opportunity details Saved Successfully!", "success");
OpportunityMstList();
GetOpportunityMstList();
location.reload();
$("#myModal").modal('hide');
},
});
after adding this on the form submit button click you have to add this for creating blob file when you post data without image file.
jQuery(document).on('click', 'button#saveOpportunity', function (e) {
e.preventDefault();
if ($("#OpportunityForm").validate().form()) {
if (zdrop.files.length == 0) {
var blob = new Blob();
blob.upload = { 'chunked': zdrop.defaultOptions.chunking };
zdrop.uploadFile(blob); // just submit the form
} else if (zdrop.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
zdrop.processQueue();
}
}
});

Not working to upload multiple images

I am using following javascript code for uploading and for compressing images but it is working for only one image.
How to compress and then upload multiple images?
what modifications are required?
html:
<input id="fileupload" type="file" name="file" multiple>
javascript:
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(function () {
'use strict';
var csrftoken = $.cookie('csrftoken');
var url = '/dashboard/{{name}}/{{name_product_type.type_product|urlencode}}/{{abc}}/';
$('#postbtn').on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
dataType: 'json',
uploadMultiple: true, // allow multiple upload
autoProcessQueue: false, // prevent dropzone from uploading automatically
maxFiles: 5,
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
// .append($('#postbtn').clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append(file.error);
}
if (index + 1 === data.files.length) {
data.context.find($('#postbtn').data(data));
// .text('Upload')
// .prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
});
}).on('fileuploadfail', function (e, data) {
$.each(data.result.files, function (index, file) {
var error = $('<span/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
I want to compress multiple images before uploading to the server. I am stuck with it please help.

Dynamically append Dropzone image upload fields

In my application I have added image upload fields dynamically using jquery append
So I use dropzone js and it not work when it append because it not initialize in document load.
So how could I load that dynamically
$(add_button).click(function(e){
$(wrapper).append(
'<div class="dropzone small-dropzone feedDropZone">' +
'<div class="dz-message" data-dz-message><p>Drop image or click to select</p></div></div>');
}
});
Dropzone code is
$('#add').on('click', '.feedDropZone', function(){
// do something here
Dropzone.autoDiscover = false;
var minImageWidth = 800, minImageHeight = 600;
$(this).dropzone({
url: base_url + "admin/feed/upload",
maxFiles: 1,
maxFilesize: 5,
acceptedFiles: ".jpeg,.jpg",
addRemoveLinks: true,
maxfilesexceeded: function (file) {
},
createImageThumbnails: true,
success: function (file, response) {
imgObject = JSON.parse(response);
},
error: function (file, response) {
},
init: function () {
this.on("thumbnail", function (file) {
if (file.width < minImageWidth || file.height < minImageHeight) {
file.rejectDimensions();
}else if(file.size/(1024*1024) > 5){
file.rejectFilesize();
}
else {
file.acceptDimensions();
}
});
}
});
});
I'm getting below error:
Error: No URL provided.
throw new Error("No URL provided.");

Validate file before upload in jQuery File Upload with upload button enabled

I'm using the latest version (9.11.2) to upload a file. I have implemented a button for the user to click to start the upload, with the add option. Now I also want to add file validation to make sure the file is an image. I found a solution to to this. This works perfectly fine for me, but only if I remove thee add option below.
$('#fileupload').fileupload({
forceIframeTransport: true,
url: nexus.admintoolapi + 'user/picture',
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
add: function (e, data) {
$uploadButton.show();
$uploadButton.on('click', function () {
data.submit();
});
},
success: function (e, data) {
},
fail: function (e, data) {
},
done: function (e, data) {
}
}).on('fileuploadprocessalways', function (e, data) {
var currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
// there was an error, do something about it
console.log(currentFile.error);
}
});
So the above code will not run the .on('fileuploadprocessalways' at all. But this will:
$('#fileupload').fileupload({
forceIframeTransport: true,
url: nexus.admintoolapi + 'user/picture',
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
success: function (e, data) {
},
fail: function (e, data) {
},
done: function (e, data) {
}
}).on('fileuploadprocessalways', function (e, data) {
var currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
// there was an error, do something about it
console.log(currentFile.error);
}
});
If I have this, then the wrong file endings will be caught and stop the file upload, but there will be no way for the user to start the upload actively.
I have also tried putting the code from fileuploadprocessalways but then the currentFile and data.files.error were undefined.
add: function (e, data) {
$uploadButton.show();
$uploadButton.on('click', function () {
var currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
// Here no error occurs ever, both conditions are undefined
console.log(currentFile.error);
} else {
data.submit();
});
},

Dropzone: Binding to init

I'm following this tutorial on mocking existing files to a Dropzone enabled form, but am having trouble hooking onto the init function. Here's what I have so far:
var imageUpload;
if ($('.js-listing__images-upload').length) {
imageUpload = new Dropzone('.js-listing__images-upload', {
addRemoveLinks: true,
maxFiles: 5,
maxFilesize: 3,
acceptedFiles: 'image/jpeg,image/png,image/gif'
});
imageUpload.on('init', function() {
var listingID, thisDropzone;
console.log('dropzone init');
thisDropzone = this;
listingID = $('#manage-images').data('listing');
$.ajax({
url: dashboard.images.list,
data: {
listing: listingID
},
success: function(data) {
console.log('ajax for list done');
$.each(data, function(key, value) {
var mockFile;
mockFile = {
name: value.name,
size: value.size
};
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, '/uploads/thumb/listings/' + value.name);
});
}
});
});
}
None of my console.log() fire, but I'm unsure as to what the issue could be. Following Dropzone's config, I should be able to hook onto events using simple on mechanisms. Thanks all!
Update
The following does work:
# When images are removed
# Dropzone
imageUpload.on 'removedfile', (file) ->
if file.xhr
imageID = JSON.parse file.xhr.response
$.ajax
url: dashboard.images.destroy
data: { image: imageID }
success: () ->
return
So it's something about the init function that I'm having trouble with.
The init function can be binded directly to your new Dropzone instantiation:
if $('.js-listing__images-upload').length
imageUpload = new Dropzone(
'.js-listing__images-upload',
addRemoveLinks: true
maxFiles: 5
maxFilesize: 3
acceptedFiles: 'image/jpeg,image/png,image/gif'
init: ->
thisDropzone = this
$.ajax
url: dashboard.images.list
data: { listing: $('#manage-images').data('listing') }
success: (data) ->
$.each data, (key, value) ->
mockFile =
name: value.name
size: value.size
thisDropzone.options.addedfile.call thisDropzone, mockFile
thisDropzone.options.thumbnail.call thisDropzone, mockFile, '/uploads/thumb/listings/' + value.name
return
return
return
)

Categories