Dropzone createThumbnailFromUrl() issue - image

I need to add pre-existing image files to dropzone by using Laravel 5.4. This is why I use createThumbnailFromUrl() function. But it does not generate images properly. Instead it shows them in blank way. I used that link (jsfiddle) for that purpose. I googled a lot, tried several ways, but it did not help:
Below is my code:
<script type="text/javascript" src='{{asset("js/dropzone/min/dropzone.min.js")}}'></script>
<script type="text/javascript">
Dropzone.options.addImages = {
paramName: "file", // The name that will be used to transfer the file
addRemoveLinks: true,
// The setting up of the dropzone
init:function() {
// Add server images
var myDropzone = this;
var existingFiles = [
{ name: "Filename 1.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 2.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 3.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 4.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 5.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' }
];
for (i = 0; i < existingFiles.length; i++) {
// alert(existingFiles[i].imageUrl);
myDropzone.emit("addedfile",existingFiles[i]);
myDropzone.files.push(existingFiles[i]);
myDropzone.createThumbnailFromUrl(existingFiles[i], existingFiles[i].imageUrl, function() {
myDropzone.emit("complete", existingFiles[i]);
}, "anonymous");
}
},
};
</script>
Here is the result :( :
P.S: Any kind of help would be appreciated.

had the same issue with dropzone 5.3
this fixed it for me
let mockFile = { name: "Loaded File", dataURL: relURL };
dropzoneInst.files.push(mockFile);
dropzoneInst.emit("addedfile", mockFile);
dropzoneInst.createThumbnailFromUrl(mockFile,
dropzoneInst.options.thumbnailWidth,
dropzoneInst.options.thumbnailHeight,
dropzoneInst.options.thumbnailMethod, true, function (thumbnail)
{
dropzoneInst.emit('thumbnail', mockFile, thumbnail);
});
dropzoneInst.emit('complete', mockFile);

I am attaching for reference my solution, based on many previous answers, but mostly on Raphael Eckmayer. This is how it is done to make it work well with Django 3.0.5 and dropzone.js 5.7.0. Maybe it is not the best solution, but it works.
I am sending my current images from Django view using new template tag json_script that packs my list of files prepared in Django into JSON. Basically in my template I have this:
{{ images|json_script:"images" }}
Then I process this in my script. Here is entire script from my site, hope that will help someone.
EDIT:
I had an issue with this code that if I add new pictures to the dropzone together with the old one from database I got this form submitted twice. In first pass I get pictures from dropzone.js, but also all fields since I am copying them from the form. And then, on second pass, I am submitting form again but now without pictures. My view actually was handling this well and storing data, but when I started to write down how to handle removed pictures on form edit I had issue with this, so I decided to handle this differently. Please note that code is now changed and instead of submitting form twice I am sending entire form and pictures with dropzone, but after successmultiple I am just redirecting to other page. Everything is updated and stored then. So the change is in the successmultiple part.
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Dropzone.autoDiscover = false;
var first_time = true;
var old_images = JSON.parse(document.getElementById('images').textContent)
var myDropzoneX = new Dropzone("div#mydropzone", {
autoProcessQueue: false,
url: "{% url 'site_report_edit' report_id=1 %}",
addRemoveLinks: true,
thumbnailWidth: 400,
thumbnailHeight: 400,
uploadMultiple: true,
parallelUploads: 12,
init: function() {
var myDropzone = this;
var addButton = document.getElementById("submit-btn");
if (old_images) {
console.log(old_images);
for (x in old_images) {
var mockFile = {
name: old_images[x].name,
size: old_images[x].size,
kind: 'image',
dataURL: old_images[x].urlich,
accepted: true
}
myDropzone.files.push(mockFile);
myDropzone.emit('addedfile', mockFile);
createThumbnail(mockFile);
console.log(old_images[x].name, old_images[x].urlich);
}
function createThumbnail(temp) {
myDropzone.createThumbnailFromUrl(temp,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod, true, function (thumbnail) {
myDropzone.emit('thumbnail', temp, thumbnail);
myDropzone.emit("complete", temp);
});
}
myDropzone._updateMaxFilesReachedClass();
}
addButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
document.getElementById("dropzone-form").submit();
}
});
this.on("successmultiple", function (files, response) {
setTimeout(function (){
{#document.getElementById("dropzone-form").submit();#}
window.location.href = "/admin/report/{{ report_id }}";
}, 1000);
});
},
sending: function (file, xhr, formData) {
var formEl = document.getElementById("dropzone-form");
if (first_time) {
for (var i=0; i<formEl.elements.length; i++){
formData.append(formEl.elements[i].name, formEl.elements[i].value)
first_time = false;
}
}
formData.append('csrfmiddlewaretoken', getCookie('csrftoken'));
formData.append("image", file.name);
}
});
</script>
Please note that there are some comments and some writing to console.log, but you can obviously get rid of this.

I had the same problem. Use these files:
https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.js
https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.css
It worked for me.

I know it's a bit late, however I was facing the same issue. The problem I was having was a race condition where only the last thumbnail was loaded and the others were stuck before completing, because i changed before createThumbnailFromUrl was getting it's data. Putting the call inside function did the trick for me:
for (var i = 0; i < images.length; i++) {
var temp = { name: images[i], dataURL: images[i] };
myDropzone.files.push(temp);
myDropzone.emit("addedfile", temp);
createThumbnail(temp);
}
function createThumbnail(temp) {
myDropzone.createThumbnailFromUrl(temp,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod, true, function (thumbnail) {
myDropzone.emit('thumbnail', temp, thumbnail);
myDropzone.emit("complete", temp);
});
}
My answer is inspired by BLitande's, which helped me getting it to kind of work in the first place.

Related

vuejs not rending data 2nd time when data as updated using ajax

Im using vue js to update a few things on my page, its real simple use case
Vue.component('my-component', {
template: '.....<a v-on:click="myfunction">data</a>{{stuff}}'
data: {
stuff: 0
}
mounted(){
let __this = this;
axios.....then(function (data){ __this.stuff = 1l }); // works
}
methods: {
myfunction: function(){
this.stuff = 2; /// dosnt work. template not rendered
}
}
});
Any particular way to set the variable to detect changes or any pointers ? thanks.
For reusable components, your data field should actually be a function that returns the data object:
Vue.component('my-component', {
template: '.....<a v-on:click="myfunction">data</a>{{stuff}}',
data() {
return {
stuff: 0
};
},
mounted(){
let __this = this;
axios.....then(function (data){ __this.stuff = 1l }); // works
},
methods: {
myfunction: function(){
this.stuff = 2; // should work now
}
}
});
Please review the relevant section of the Vue.js documentation for more information concerning this issue.

JSON and HTML troubles

i'm currently having some troubles with displaying the information from a JSON file to html. I'm currently using AJAX to get the data from the JSON file.
The main problem that i'm facing is with displaying all the data into one div.
function Test(){
request.open('GET','/json/anime.json');
request.onreadystatechange = function() {
if((request.readyState===4) && (request.status===200)) {
var json = JSON.parse(request.responseText);
for(var title in json.Title ) {
for(var ep in json.Episode) {
for(var img in json.Image) {
for(var link in json.Link) {
_title = json.Image[title];
episode = json.Image[ep];
image = json.Image[img];
_link = json.Image[link];
var div = document.createElement('div');
div.className = 'card card-inverse';
div.innerHTML = `<img class="card-img img-fluid img-responsive" src="${image}" data-toggle="modal">`;
document.getElementById('anime').appendChild(div);
}
}
}
}
}
}
request.send();
}
The JSON file looks like this...
{
Episode: [
...
],
Image: [
...
],
Link: [
...
],
Title: [
...
]
}
The way above is working if i'm only looping over one of the four arrays, however crashes chrome when trying to do the above task.
Any help would be appreciated.
Thanks
I decided to take a different approach moving away from ajax a little and moving more towards jquery. Below is what has so far worked out for me. Thanks to the people who commented above, really helped me think of ways to tackling it.
function DisplayCards() {
var i = 0;
$.getJSON('/json/anime.json', function(data) {
$.each(data, function(index) {
for(key in data[index]){
e = data.Image.length;
console.log(e);
if(i < e)
{
image = data.Image[key];
link = data.Link[key];
console.log(i += 1);
var div = document.createElement('div');
div.className = 'card card-inverse';
div.innerHTML = `<img class="card-img img-fluid img-responsive" src="${image}" data-toggle="modal">`;
var p = document.createElement('p');
p.innerHTML = 'id="wrapper" class="text"';
document.getElementById('anime').appendChild(div);
}
}
console.log(data);
});
});
}

Ckeditor Get Content From Iframe

I have a iframe and i'm trying to use Dialog to get data in Iframe and output to current html, but i don't know how to get Ckeditor Content from the Iframe.
I tried to using CKEDITOR.instances['editor'].getData(); but look like cannot get it.
This is my code:
<textarea class='editor' name='description' id='description'></textarea>
$( "#dialog_custom" ).dialog({
autoOpen: false,
modal: true,
height: 768,
width: 1024,
buttons: {
Add: function() {
var model = $('.dialog_custom').contents().find('#model').val();
var product_id = $('.dialog_custom').contents().find('#product_id').val();
var product_name = $('.dialog_custom').contents().find('#product_name').val();
var qty = $('.dialog_custom').contents().find('#qty').val();
var total = $('.dialog_custom').contents().find('#total').val();
var category = $('.dialog_custom').contents().find('#category').val();
if(qty=='') { qty = '0'; }
if(total=='') { total = '0.00'; }
if(model=='') {
alert('Please input the correct Model Number.');
} else {
$(".product").append(InsertTableGetFromIframe);
$('.delete_custom_row').click(function() {
if(confirm("Are you sure want to delete this data?")) {
$(this).parents('.custom_row').next('.parts_row').remove();
$(this).parents('.custom_row').remove();
}
});
$('.dialog_custom').contents().find('#model').val('');
$('.dialog_custom').contents().find('#product_id').val('');
$('.dialog_custom').contents().find('#product_name').val('');
$('.dialog_custom').contents().find('#qty').val('');
$('.dialog_custom').contents().find('#total').val('');
$('.dialog_custom').contents().find('#category').val('');
$(this).dialog("close");
i++;
}
},
Close: function() {
$(this).dialog("close");
}
}
});
$( "#open_custom" ).click(function() {
$( "#dialog_custom" ).dialog( "open" );
});
</script>
Finally, I found out the solution to get the content in the iframe, i used jquery to submit the form then POST the value on the field and get it by Jquery again.
It's the most simple way that i found, actually I think we have another way better to do it...

IE not reading GET success after POST

I cannot seem to find out why IE does not read my success on get after the post. I have tried cache: false, with no luck. This works in all other browsers, just not IE.
$.ajaxSetup({ cache: false });
num = $('#num').val();
phone = $('#phone').val();
$.post("post.php?"+$("#MYFORM").serialize(), {
}, function(response){
if(response==1 && codeVal == 1 && telVal == 1)
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Η αποστολή πραγματοποιήθηκε</label>');
change_captcha();
clear_form();
$.ajax({
type:'get',
cache: false,
url: "http://web.somesite/submit_code.php",
dataType: 'html',
data:{ user: "one", pass: "mtwo", source: "WEB", receipt: num, msisdn: phone},
success: function(data) {
var qsFull = "http://web.somesite.gr/submit_code.php?" + data;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
}
});
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="error" id="after_submit">Error! in CAPTCHA .</label>');
}
});
OK, I tried adding an error after the success and I see that I get my pop up as I should be, but the value of qs.message is 0. Why would I get error and not success, when it is successful in other browsers.
I found the answer, It has to do with IE not being flexible with cross domains and such, so I added a XDomainRequest like so
if (jQuery.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
var my_request_data = { user: "M1web", pass: "m!", source: "WEB", receipt: num, msisdn: phone};
my_request_data = $.param(my_request_data);
if (xdr) {
xdr.onerror = function () {
alert('xdr onerror');
};
xdr.ontimeout = function () {
alert('xdr ontimeout');
};
xdr.onprogress = function () {
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
};
xdr.onload = function() {
//alert('onload ' + xdr.responseText);
var qsFull = "http://web.web.gr/submit_code.php?" + xdr.responseText;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
callback(xdr.responseText);
};
xdr.timeout = 5000;
xdr.open("get", "http://web.web.gr/submit_code.php?" + my_request_data);
xdr.send();
} else {
}
}
I unfortunately had to do a crash course in legacy IE behavior, and this post was very helpful. Here are some other links to help those having to deal with these issues:
Microsoft's Documentation of their XDomainRequest object
An internal blog post covering some of XDomainRequest's idiosyncrasies
Here's a function I use as a fallback where necessary:
// This is necessary due to IE<10 having no support for CORS.
function fallbackXDR(callObj) {
if (window.XDomainRequest) {
var xdrObj = new XDomainRequest();
xdrObj.timeout = callObj.timeout;
xdrObj.onload = function() {
handleSuccess(xdrObj.responseText);
};
xdrObj.onerror = function() {
handleError(xdrObj);
};
xdrObj.ontimeout = function() {
callObj.xdrAttempts = callObj.xdrAttempts++ || 1;
if (callObj.xdrAttempts < callObj.maxAttempts) {
fallbackXDR(callObj);
}
};
xdrObj.onprogress = function() {
// Unfortunately this has to be included or it will not work in some cases.
};
// Use something other than $.param() to format the url if not using jQuery.
var callStr = callObj ? '?'+$.param(callObj.urlVars) : '';
xdrObj.open("get", callObj.url+callStr);
xdrObj.send();
} else {
handleError("No XDomainRequest available.", callObj);
}
}//fallbackXDR()

Loading google datatable using ajax/json

I can't figure out how to load a datable using ajax/json. Here is my json code in a remote file (pie.json)
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
}
This is what I have tried so far but it doesn't work.
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["piechart"]});
function ajaxjson() {
jsonreq=GetXmlHttpObject();
jsonreq.open("GET", "pie.json", true);
jsonreq.onreadystatechange = jsonHandler;
jsonreq.send(null);
}
function jsonHandler() {
if (jsonreq.readyState == 4)
{
var res = jsonreq.responseText;
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(res, 0.6)
var chart = new google.visualization.PieChart(document.getElementByI('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
} // end drawChart
} // end if
} // end jsonHandler
function GetXmlHttpObject()
{
var xmlHttp=null;
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
Things work perfectly if I replace the 'res' variable with the actual code in pie.json.
Any help would be greatly appreciated.
Just a guess because I'm unfamiliar with the google objects you are using, but I'm pretty sure responseText just returns a string. JavaScript can't natively parse JSON (only XML to the best of my knowledge), so you'd have to eval("var res = " + jsonreq.responseText).
I hope this helps.
if I were in you, I'll use jQuery to save some code:
$.getJSON("pie.json", function(data) {
drawWanChart(data);
});
and here the function that draws your chart:
function drawWanChart(jsonData)
{
jsonData = jQuery.parseJSON(jsonData);
if(jsonData != null)
{
data = new google.visualization.DataTable(jsonData);
chart = new Google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data, null);
}
}
Please refer to official documentation:
$.getJSON
PieChart on Google Playground

Resources