update value of hidden before submit [closed]

1

I'm trying to update two hiddens with a base64 code from the html2canvas plugin, but it does not update and on the other page where the form is received it gets caught by $_POST both fields hidden plus does not show base64 code %.

html2canvas(document.getElementById("areamontagem"), {
    "useCORS": true,
      onrendered: function(canvas) {
          $( "#baseimg" ).val(canvas.toDataURL("image/png"));
      }
    });
    //print area total sem MOLDE
    html2canvas(document.getElementById("areamontagem"), {
    "useCORS": true,
      onrendered: function(canvas) {
          $( "#baseimg" ).val(canvas.toDataURL("image/png"));
      }
    });
    $( "#myform" ).submit();
    
asked by anonymous 11.11.2016 / 20:38

1 answer

2

The problem happens because the code that generates the base64 image is asynchronous, that is, it runs outside the timeline of your code. I explain better:

// o javascript executa o html2canvas e ...
html2canvas(document.getElementById("areamontagem"), {
    "useCORS": true,
      onrendered: function(canvas) {
          $( "#baseimg" ).val(canvas.toDataURL("image/png"));
      }
});

// logo em seguida chama o html2canvas novamente e ...
html2canvas(document.getElementById("areamontagem"), {
    "useCORS": true,
      onrendered: function(canvas) {
          $( "#baseimg" ).val(canvas.toDataURL("image/png"));
      }
});

// logo em seguida chama o submit do form.
$( "#myform" ).submit();

Some time later the callback of html2canvas returns, but it is already too late and the page has already been submitted with the empty empty field.

Or you use Promises (it's in jQuery and it's simple to use, although it's not easy to understand at first) or you chain calls within callbacks, like this:

html2canvas(document.getElementById("areamontagem"), {
    "useCORS": true,
      onrendered: function(canvas) {
          $( "#baseimg" ).val(canvas.toDataURL("image/png"));

          html2canvas(document.getElementById("areamontagem"), {
              "useCORS": true,
                onrendered: function(canvas) {
                    $( "#baseimg" ).val(canvas.toDataURL("image/png"));
                    $( "#myform" ).submit();
                }
          });
      }
});

This way javascript calls the first html2canvas, and when it returns, it calls the second and when that returns its form will be submitted.

    
14.11.2016 / 19:40