html2canvas in JQuery isn't calling onrendered - javascript

I am trying to take a screenshot of a div inside my html on a button click that also submits that information. I then need this screenshot to be saved onto the server via the script.php. At first I thought it just wasn't catching an error so I put in the console logs for Starting and Rendered. Starting shows but Rendered does not.
Below is my script
html2canvas($(".final-print")[0], {
console.log('starting');
onrendered: function(canvas) {
console.log('Rendered');
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('Check Server For Image');
});
}
});
Below is my html
<div class="final-print" style="width:400px;height:300px;padding: 9px;background-image: url('images/back.jpg');background-position: center;background-repeat: no-repeat;background-size: cover;border: 3px solid #000000;"></div>
Inside of the console it says 'Starting' with no errors being thrown. Then nothing else happens. The script is called on a button click. After a few hours of research of my own I couldn't really find anything useful to helping fix this issue.

Related

JQuery & Ajax disable click

I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});

Ajax anchor Link trigger not working

I am using html2canvas javascript to convert html div to image file. All script are working good and it converts html div to image properly.
But when I am adding response(anchor link) to href and triggering it using ajax it is not triggering anchor link.
Here is my code,
Html code:
<div id="mainDiv">
<h1>Heading H1</h1>
<p>Download Image using ajax and php</p>
</div>
<div>
<a id="download">Download Image</a><br/>
<a id="download-image" href="" download>Download</a>
</div>
Ajax code
<script>
$('#download').on('click', function () {
html2canvas([document.getElementById('mainDiv')], {
onrendered: function (canvas) {
var imagedata = canvas.toDataURL('image/png');
var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_image.php',
data: {
imgdata:imgdata
},
type: 'post',
success: function (response) {
$('#download-image').attr('href', response).trigger('click');
//$('#downlaod-image').trigger('click');
}
});
}
});
});
</script>
Clicking the link will actually reload your page. It will still execute html2canvas(), but the response from the Ajax call will never be processed, as by that time the page has already been reloaded.
So cancel the default hyperlink action by adding a return false just before the end of the click handler (after the call to html2canvas).

Loading image using AJAX Request won't work

I need to use an AJAX request to load a gif image from this source:
http://edgecats.net
Everytime I try to do so and use the response on the image source as:
$('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + data);
It won't work!
When copying the response using firefox's devtools and using:
data:image/gif;base64,<PASTE_HERE>
Everything works like a charm!
How can I figure out how to turn my response into an image correctly?
This is my AJAX request code:
function getCatImg() {
return $.ajax({
type: 'GET',
url: 'http://edgecats.net',
datatype:"image/gif"
});
}
getCatImg().success(function(data) {
$('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + data);
});
You don't need to use Ajax on this particular task. But, if you insist, you must use a trick to make this work:
$(document).ready(function() {
$.ajax('http://edgecats.net', {
success: function(r) {
var reader = new FileReader();
reader.onload = function(e) {
$('img').prop('src', e.target.result);
};
reader.readAsDataURL(new Blob([r]));
}
});
});
I am not familiar with the cats on the edge, but as I've looked at the site, the response was not base64 encoded, so it won't work that way.
How about setting the image src to edgecats.net
$('#cat-thumb-1').attr('src', 'http://edgecats.net');

How to detect if image URL doesn't work

I got a javascript problem. I'm building a website which communicates with a MovieDB-API which will sometimes return broken URLs.
Is there any way to detect whether the URL returned by the API is going to lead to an empty page? Perhaps by checking retroactively if the image defaulted to the "alt"-attribute? Obviously, since the alt-text is showing, the program is "aware" of the fact that the URL fails.
In case the URL is broken, I want to have the IMG-variable replaced by the path to a local default-image.
CSS with javascript enabled
<img src="image.jpg" onerror="this.src='alternative.jpg';">
OR
jquery
// Replace source
$('img').error(function(){
$(this).attr('src', 'missing.png');
});
// Or, hide them
$("img").error(function(){
$(this).hide();
});
Edit
$(document).ready(function () {
$('img').error(function () {
$(this).addClass('noImg');
});
});
.noImg {
position: relative;
background: url() no-repeat center center; // or simple background color
height: 100px;
width: 100px;
content: "Your content";
margin: 0 10px 10px 0;
}
You can use the onerror event to check the URL and see if the image can be loaded.
var url = 'http://www.somesite.com/image.jpg';
var img = new Image();
img.onerror = function() {
console.log('image could not be loaded, setting default placeholder');
image_tag.src = '/my_default_placeholder.gif';
}
img.src = url;
without any posted code, it's just a general example of how it would work,
You could try to do an Ajax request for every image. If it does exist it will return success. Otherwise it throw an error and you can put the desired image in this place.
jQuery Ajax snippet:
$.ajax({
type: "GET",
url: url_to_img,
success: function(result) {
console.log("SUCCESS");
$('#img-1234').attr('src', url);
},
error: function(result) {
console.log("ERROR");
// url broken
$('#img-1234').attr('src', '/img/noImg.png');
}
});
Hope it helps

Desktop image drag&drop upload crashing browser

I got a form for uploading images through ajaxForm. I have implemented a function so users can drop photos from desktop (HTML5 drag&drop). Every thing works fine if photo is "small" - lets say 2mb. The problem occuress when I try to upload photos that are larger then 4mb. Chrome browser crashes.
AjaxForm
$(document).ready(function() {
$("#uploadForm").ajaxForm({
iframe: true,
dataType:"json",
beforeSubmit: function () {
$("#post .button.save").prop("disabled",true).val("Uploading...");
},
success: function (result) {
$("#FilePhotoString").val("");
$("#post").css({
"background": 'url(' + result + ') no-repeat center center',
"display": "block",
"height": $("body").height(),
"background-size": "cover"
});
$("img").attr("src",result).load(function() {
$('input[name="ImageFilePath"]').attr('value', result);
$("#post .button.save.now").prop("disabled",false).val("Publish now");
$("#post .button.save.later").prop("disabled",false).val("Publish later");
});
}
});
});
Drop
document.body.addEventListener('dragover',function(event) { event.preventDefault(); },false);
document.querySelector('#content').addEventListener('drop', function(event) {
event.preventDefault();
var reader = new FileReader();
reader.onload = function(evt) {
$("#FilePhotoString").val(evt.target.result);
$("#uploadForm").submit();
};
reader.readAsDataURL(event.dataTransfer.files[0]);
}, false);
Result returned on success is just path of uploaded photo. Any ideas what can I do so browser will not crash?
How about taking another approach, like using FormData and sending a file instead of a string.
var data = new FormData(document.getElementById('#uploadForm'));
data.append('theNameYouWantToSend', event.dataTransfer.files[0]);
then send an ajax request
$.ajax({
url:'theurl',
type:'post',
data: data,
contentType:false,
processData:false,
...
});
I think it isnt a jquery/ajax/browser problem. If you are using an apache server for example check the "upload_max_filesize = 2M" located at your php.ini.
The default size is 2mb so it fits you're problem well. The server send a timeout if you try to upload more than 2mb.

Categories

Resources