Search code examples
jqueryclickhtml2canvas

html2canvas call causes jQuery click to need two clicks for function to work


I've read all the questions with the same problem but no success.
I've tried trigger(), unbind('click'), on('click', function()), live('click'), etc

My problem is that I have to click twice on the save button to validate and submit the data to the database and return a message of 'success' or 'fail' to display error message.

JQUERY

$('.save').click(function (event) {
    // GET CATEGORIA
    var category_change = 0;
    if (!$('#new_category').val()) {
        category = $('#categoria_id').val();
    } else {
        category = $('#new_category').val();
        category_change = 1;
    }

    // GET TITLE
    var title = $('input#title').val();

    // GET IMAGE
    var target = $('#parent');
    html2canvas(target, {
        onrendered: function (canvas) {
            image = canvas.toDataURL();
        }
    });

    // GET FORMATED CODE
    var array = ["n", "e", "s", "w"];
    var format = $('#parent').html();
    var strrep = '<div class="close">X</div>';
    var strrep2 = '<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 1000;"></div>';

    var aux2 = 0;
    while (aux2 < 5) {
        $.each(array, function () {
            format = format.replace('<div class="ui-resizable-handle ui-resizable-' + this + '" style="z-index: 1000;"></div>', '');
        });
        format = format.replace(strrep, '');
        format = format.replace(strrep2, '');
        aux2++;
    }
    var code = '<div id="parent">' + format + '</div>';


    if (title != '' && $('.child').length != 0) {
        $('.db_result').html('<img src="images/loader.gif" />');
        $.post("db_prox.php", {
            category: category,
            title: title,
            image: image,
            code: code,
            category_change: category_change
        }, function (post_result) {
            alert('2');
            if (post_result == 'success') {
                $('.db_result').text('O template foi guardado com sucesso!');
                $('.continue').prop("disabled", false);
            } else {
                $('.db_result').text('Ocorreu um erro na gravação do template!');
            }
        });
    }

    // INSERIR NA BASE DE DADOS CLOSE
});

PHP db_prox.php

<?php
require_once 'includes/functions.php';

$categoria = $_POST['category'];
$title = $_POST['title'];
$image = $_POST['image'];
$code = $_POST['code'];
$nova_categoria = $_POST['category_change'];

if($nova_categoria == 1){

    $result = get_cat_last_created();
    $cat_id = mysqli_fetch_assoc($result);
    $aux_id = $cat_id['categoria_id'] + 1;
    $query = "INSERT INTO categorias (categoria_id, name) VALUES ('$aux_id', '$categoria')";
    if(mysqli_query($connection, $query)) {
        $query2 = "INSERT INTO templates (categoria_id, title, image, code) VALUES ('$aux_id', '$title', '$image', '$code')";

        if(mysqli_query($connection, $query2)) {
            echo "success";
        }
        else {
            echo "fail";
        }
    }
}else{
    $query = "INSERT INTO templates (categoria_id, title, image, code) VALUES ('$categoria', '$title', '$image', '$code')";
    if(mysqli_query($connection, $query)) {
        echo "success";
    }
    else {
        echo "fail";
    }
}
mysqli_close($connection);
?>

Solution

  • The onrendered function is asynchronous in

     html2canvas(target, {
        onrendered: function (canvas) {
            image = canvas.toDataURL();
        }
    });
    

    meaning that whatever code that is synchronously run right after that doesn't have the image variable assigned yet.

    Moving your ajax post inside the onrendered function will make it send the request once the image has been created, i.e:

     html2canvas(target, {
        onrendered: function (canvas) {
            image = canvas.toDataURL();
            $.post("db_prox.php", {
              category: category,
              title: title,
              image: image,
              code: code,
              category_change: category_change
            }, function (post_result) {
              alert('2');
              if (post_result == 'success') {
                $('.db_result').text('O template foi guardado com sucesso!');
                $('.continue').prop("disabled", false);
              } else {
                $('.db_result').text('Ocorreu um erro na gravação do template!');
              }
            });
        }
    });