Dropzone.js how to add hidden input with value to uploaded image - javascript

I am having problems with adding hidden input field to uploaded images using dropzone.js.
What i am trying to do is to use dropzonejs to upload images to the website and then having possibility with jquery sortable to drag and change order of the images.
I've managed to make it working everything so far except when i use separated input array the order of the images is not changed on drag and drop.
For this to work i need to find a way to add hidden input to the image template when image is uploaded.
Here is the code i use in .php file
<div class="form-group">
<div id="media-uploader" class="dropzone"></div>
<div id="uploaded-media" class="hidden">
</div>
</div>
Right now when image is uploaded a hidden input field is added to #uploaded-media but i need to change that and add hidden input in uploaded image template holder.
Here is what it looks like now when image is uploaded
<div id="media-uploader" class="dropzone dz-clickable ui-sortable dz-started">
<div class="dz-default dz-message">
<span>Drop files here to upload</span>
</div>
<div class="dz-preview dz-processing dz-image-preview dz-success dz-complete">
<div class="dz-image"><img data-dz-thumbnail="" alt="DSC_3771-Edit.jpg" src=""></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size=""><strong>0.9</strong> MB</span></div>
<div class="dz-filename"><span data-dz-name="">DSC_3771-Edit.jpg</span></div>
</div>
<div class="dz-progress">
<span class="dz-upload" data-dz-uploadprogress="" style="width: 100%;"></span>
</div>
<div class="dz-error-message"><span data-dz-errormessage=""></span></div>
<div class="dz-success-mark"> </div>
<div class="dz-error-mark"> </div>
<a class="dz-remove" href="javascript:undefined;" data-dz-remove="">Remove file</a>
</div>
</div>
The only small change i need is it to look like this
<div id="media-uploader" class="dropzone dz-clickable ui-sortable dz-started">
<div class="dz-default dz-message">
<span>Drop files here to upload</span>
</div>
<div class="dz-preview dz-processing dz-image-preview dz-success dz-complete">
<div class="dz-image"><img data-dz-thumbnail="" alt="DSC_3771-Edit.jpg" src=""></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size=""><strong>0.9</strong> MB</span></div>
<div class="dz-filename"><span data-dz-name="">DSC_3771-Edit.jpg</span></div>
</div>
<div class="dz-progress">
<span class="dz-upload" data-dz-uploadprogress="" style="width: 100%;"></span>
</div>
<div class="dz-error-message"><span data-dz-errormessage=""></span></div>
<div class="dz-success-mark"> </div>
<div class="dz-error-mark"> </div>
<a class="dz-remove" href="javascript:undefined;" data-dz-remove="">Remove file</a>
**<input type="hidden" name="media-ids[]" id="media-ids[]" class="media-ids" value="812">**
</div>
</div>
Here is the dropzone configuration
// Dropzone file uploader
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone ("#media-uploader", {
url: dropParam.upload,
autoProcessQueue: true,
parallelUploads: 1,
uploadMultiple: false,
maxFilesize: 3,
acceptedFiles: 'image/*',
addRemoveLinks: true,
maxFiles: 10,
success: function (file, response) {
file.previewElement.classList.add("dz-success");
file['attachment_id'] = response; // push the id for future reference
$('#uploaded-media').append( $('<input type="hidden" name="media-ids[]" id="media-ids[]" class="media-ids" value="' + response +'">') );
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
// update the following section is for removing image from library
removedfile: function(file) {
var attachment_id = file.attachment_id;
jQuery.ajax({
type: 'POST',
url: dropParam.delete,
data: {
media_id : attachment_id
}
});
$('input.media-ids[type=hidden]').each(function() {
if ($(this).val() == attachment_id) {
$(this).remove();
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});

I found the solution, the code below will add an input field to each uploaded image upon successful upload
myDropzone.on("success", function(file, response) {
$(file.previewElement).append( $('<input type="hidden" name="media-ids[]" id="media-ids[]" class="media-ids dz-media-id" value="' + response +'">') );
});

$("div#js-dropzone").dropzone({
url: "/api/mmm/orders/fileupload",
method: 'POST',
maxFilesize: 5, // MB
previewTemplate: previewTemplate,
success: function (response) {
$(response.previewElement).append('<input type="hidden" name="fileupload" value="' + JSON.parse(response.xhr.response).fileName + '" />');
}
});

Related

Ajax status update in one page with one button

I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code

image show in modal by croppie.js library

I am using croppie.js library to crop a image in modal and save via ajax in database.
It is working when input type file. But do not need it after click on file type. I have an img tag with src and when I click on this image then related image should be in modal and I can crop image.
My img tag is:
<img src="pic1.jpg" id="profilenewpic" width="auto" height="140px" />
When I click on this image then my croppie libraray should work.
<script type="text/javascript">
// start profile crop
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:230,
height:230,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#profilenewpic').on('click', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log(event.target.result);
});
}
reader.readAsDataURL(this.files[0]);
$('#uploadimageModal').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:"../../upload.php",
type: "POST",
data:{"image": response},
success:function(data)
{
$('#uploadimageModal').modal('hide');
$('#profile_id').hide();
$('#show_image').attr('src', data);
$('#show_image').show();
}
});
})
});
});
// end profile crop
</script>
My modal is:
<div id="uploadimageModal" class="modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Crop & Upload Image</button>
</div>
</div>
</div>
</div>
</div>
</div>

multiple upload image using dropzone in codeigniter

hello im newbie and need some help in here, im using sublime text 3 and im using codeigniter version 3.1.8 im having problem and the problem is i dont know how to upload multiple image in dropzone ? and im using a template for dropzone.js
here is my view code
<div class="x_content">
<div class="">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Dropzone multiple file uploader</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<i class="fa fa-wrench"></i>
<ul class="dropdown-menu" role="menu">
<li>Settings 1
</li>
<li>Settings 2
</li>
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div id="my-dropzone" class="dropzone">
<div class="dz-message">
<h3>Drop files here</h3> or <strong>click</strong> to upload
</div>
<input type="hidden" name="facility" id="facilityid" value="<?php echo $row->facilityid;?>">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="left_col" role="main" >
<a class="btn btn-sm btn-info pull-right buttonnext"
href="">Next <i class="fa fa-upload"></i>
</a>
</div>
<?php } ?>
and here is my script
<script>
Dropzone.autoDiscover = false;
Dropzone.prototype.defaultOptions.dictMaxFilesExceeded = "Can't upload more images.";
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?php echo site_url("facilitycontrol/insertuploaddetail") ?>",
acceptedFiles: "image/*",
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: "post",
url: "<?php echo site_url("faciltycontrol/remove") ?>",
data: { file: name },
dataType: 'html'
});
// remove the thumbnail
var previewElement;
return (previewElement = file.previewElement) != null ? (previewElement.parentNode.removeChild(file.previewElement)) : (void 0);
},maxFiles: 10,
init: function() {
this.on("maxfilesexceeded", function(file){
alert("you can't upload more images.");
}),
this.on("success", function(file, xhr){
var texting = $('#facilityid').val();
// alert(texting);
$(".buttonnext").show();
var data = file.xhr.response;
$(".buttonnext").click(function() {
/* Act on the event */
// alert(data);
window.location = "<?php echo base_url(); ?>facilitycontrol/descriptionview/"+data+"/"+texting;
});
})
},
});
And this is my Controller
public function insertuploaddetail(){
if ( ! empty($_FILES))
{
$config["upload_path"] = './assets/images/facility/';
$config["allowed_types"] = "gif|jpg|png";
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('file');
$fileData = $this->upload->data();
print_r($fileData['file_name']);
}
}
im just newbie,I really need your help
Please try using your normal form tag to wrap your form.
<form action="" method="post" enctype="multipart/form-data">
<!-- form content starts -->
<!-- form content end -->
</form>
The enctype will allow form upload by php.

Adding image id to each image in preview template in dropzone .js

I just want to add image id to each image that are uploaded using dropzone.js
currently preview template is like this
<div class="dz-preview dz-image-preview" id="1">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name="">car-menu03.jpg</span></div>
<div class="dz-size" data-dz-size=""><strong>85.9</strong> KiB</div>
<img data-dz-thumbnail="" alt="car-menu03.jpg" src="http://server1/akhil/workspace/XENSALE/assets/uploads/images/cars/2/car-menu03.jpg">
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress=""></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage=""></span></div>
<a class="dz-remove" href="javascript:undefined;" data-dz-remove="">Remove</a>
</div>
This code get all images from the server and initialize the dropzone container.
I hope this help you
// Initialize dropzone
init: function() {
thisDropzone = this;
// Call server to get all images in JSON format {id, filename, imagesize}
$.get("get-all-images", function(data) {
$.each(data.data, function(key,value){
var mockFile = { name: value.filename, size: value.imagesize };
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, value.file);
// On the created element added the id property
$(mockFile.previewElement).prop('id', value.id);
});
});
}

Getting attribute of jQuery Dropzone DIV

I have dropzone (v3.7.1) divs in each of my bootstrap tabs.
How can I upload all files in all dropzones only after clicking on submit button (not using form for each dropzone)? When I set autoProcessQueue to false and try to attach listener, an error saying unable to attach an event to undefined shows up...
How do I get attributes of a dropzone object e.g. rel="6" of the first dropzone? Attempts to use this.attr('rel') / $(this).attr('rel') results in 'undefined'...
HTML
<form class="my-form" method="post">
<input type="text" name="form-input-1" id="form-input-1" />
<input type="text" name="form-input-2" id="form-input-2" />
<div class="tab-content">
<div class="tab-pane active" id="ic_6">
<h3>Overview</h3>
<div rel="6" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_1">
<h3>Living Room</h3>
<div rel="1" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_2">
<h3>Kitchen</h3>
<div rel="2" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_3">
<h3>Bathroom</h3>
<div rel="3" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_4">
<h3>Bedroom</h3>
<div rel="4" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_5">
<h3>Outdoors</h3>
<div rel="5" class="dropzone" id="my-dropzone"></div>
</div>
</div>
<button type="submit">Submit</button>
</form>
JS
Dropzone.options.myDropzone = {
url: "upload.php",
maxFilesize: 2, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("addedfile", function(file) {
//== divider ==//
var dividerElement = Dropzone.createElement("<div> </div>");
file.previewElement.appendChild(dividerElement);
//== caption input : still trying to figure capturing this ==//
var captionInput = Dropzone.createElement("<input type='text' name='caption' maxlength='50' placeholder='Enter a caption' />");
file.previewElement.appendChild(captionInput);
});
this.on("removedfile", function(file) {
$.ajax({
url: "delete_temp_files.php",
type: "POST",
data: { filename: file.name }
});
});
}
}
I know this is an old post, but the solution to accessing attributes on the original element is
console.log($($(this)[0].element).attr("rel"));
If your html code is:
<div class="dropzone" data-name="mypics"></div>
pure javascript:
new Dropzone("div.dropzone", {
url: "<backend-url>",
success: function (file, response) {
// Get "data-name" attribute here
var name = this.element.getAttribute("data-name");
}
});

Categories