Search code examples
jqueryajaxsignaturepad

Using signature_pad with bootstrap modal and ajax saving


Using this code to plug a signature block into a form. Using a standard HTML form, this works great (ie, a non-ajax call, but a form submitting to a URL).

But what I am now trying to do, is have the canvas in a bootstrap modal element on the page, which is initially hidden. I then set the modal to show, and initiate the canvas. Then - when the form (including the filled signature) is submitted - the form data is saved via ajax (jQuery).

My issue is that I keep getting errors relating to the canvas/signaturePad not being defined - signaturePad is not defined when triggering the ajax save.

This is the signature code, included in the bootstrap modal:

 <div id="signature-pad" class="signature-pad">
    <div class="signature-pad--body">
      <canvas></canvas>
    </div>
  </div>

This is the jQuery code, for when I launch the modal (which works perfectly - I can sign on the canvas):

       $("#ModalActionCost").modal('show');

       var wrapper = document.getElementById("signature-pad");
        var canvas = wrapper.querySelector("canvas");
        var signaturePad = new SignaturePad(canvas, {
          backgroundColor: 'rgb(255, 255, 255)'
        });

And this is the code when I save the form contents:

    $("#trigger").click(function(e){

        var dataURL = signaturePad.toDataURL();   <-- this is the line I get the error on.
        $("#hiddenSignature").val(signaturePad.toDataURL("image/png").replace("data:image/png;base64,", ""));

        var hiddenSignature = $("#hiddenSignature").val();
        // ajax call follows.
        ......
   });

Again the error I am getting is: signaturePad is not defined

To try get around this error, I thought I need to initiate the canvas again (call var signaturePad...) when saving via ajax - which did indeed work, and the pad blob value was sent - but of course I get a blank canvas, seen as it's been wiped when re define.

I put together a simplified version of the flow of jsfiddle - which DOES seem to work enter link description here, but i cant figure out why my version above does not.


Solution

  • My Solution, for others:

    Move the instance of creating the signature_pad - from the function that opens the modal - to onload of the page in general:

        var wrapper = document.getElementById("signature-pad");
        var canvas = wrapper.querySelector("canvas");
        var signaturePad = new SignaturePad(canvas, {
          backgroundColor: 'rgb(255, 255, 255)'
        });