I have the following JS code. Problem is the the form always submit before the then function. I want the form to only submit after the then function.
How do I do that? Thanks
$('#form').submit(function (e) {
e.preventDefault();
html2canvas(document.getElementById('uty'), {
useCORS: true,
}).then(function (canvas) {
var img = canvas.toDataURL("image/png");
document.getElementById('input').value = img;
});
});
To solve this you can store a reference to the form
element in the outer submit
handler function, then call submit()
on that within the then()
block. Something like this:
$('#form').submit(function (e) {
e.preventDefault();
var form = this;
html2canvas(document.getElementById('uty'), {
useCORS: true,
}).then(function(canvas) {
var img = canvas.toDataURL("image/png");
document.getElementById('input').value = img;
form.submit();
});
});
Note I'm calling the DOM submit
function, not jQuery's. jQuery's would re-run the submit handler, the DOM's won't.