laravellaravel-admin

CSRF token error when generating data from canvas


I'm using a package called laravel-admin.

I created a custom signature field with popular SignaturePad package, the data got converted into image successfully. However when I tried to submit the form I've got an error saying CSRF token miss match.

Here's my code for rendering SignaturePad class:

public function render()
{
    $this->script = <<<EOT
    var canvas = document.getElementById('signature-pad');

    // Adjust canvas coordinate space taking into account pixel ratio,
    // to make it look crisp on mobile devices.
    // This also causes canvas to be cleared.
    function resizeCanvas() {
        // When zoomed out to less than 100%, for some very strange reason,
        // some browsers report devicePixelRatio as less than 1
        // and only part of the canvas is cleared then.
        var ratio = Math.max(window.devicePixelRatio || 1, 1);
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext("2d").scale(ratio, ratio);
    }

    window.onresize = resizeCanvas;
    resizeCanvas();

    var signaturePad = new SignaturePad(canvas, {
        backgroundColor: 'rgb(255, 255, 255)' // necessary for saving image as JPEG; can be removed is only saving as PNG or SVG
    });

    $('button[type="submit"]').click(function() {
        console.log(signaturePad.toDataURL());
        $('input[type=hidden]').val(signaturePad.toDataURL());
    });

    EOT;
    return parent::render();
}

If I remove the line below then I won't get it, but obviously my data is not sent. The way it works is I converts the value of the image and put it to the hidden input field to be sent. Can anyone help?

$('button[type="submit"]').click(function() {
    console.log(signaturePad.toDataURL());
    $('input[type=hidden]').val(signaturePad.toDataURL());
});

Solution

  • Apparently I forgot that laravel gives hidden input containing CSRF token that I am changing all together with jQuery code

    $('button[type="submit"]').click(function() {
        console.log(signaturePad.toDataURL());
        $('input[type=hidden]').val(signaturePad.toDataURL());
    });
    

    Thanks everyone