update Hidden value before Submit

Asked

Viewed 98 times

1

I’m trying to update two hiddens with a Base64 code coming from the plugin html2canvas, but it does not update and on the other page where the form is received picked up by $_POST the two fields hidden but does not show the code base64.

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();

1 answer

2

The problem is because the code that generates the image in Base64 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’s too late and the page has already been submitted with the empty Hidden field.

Either you use Promises (it’s in jQuery and it’s simple to use, although it’s not simple to understand at first) or you chain the calls inside the 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 it returns your form will be submitted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.