yeeeeee
yeeeeee

Reputation: 163

Save a `toDataURL` Image to Server

I've tried implementing signature_pad, but I honestly don't understand it.

How do I return an image value and post it to my server?

EDIT:

I've tried decoding:

JavaScript "app.js":

saveButton.addEventListener("click", function (event) {
    if (signaturePad.isEmpty()) {
        alert("Please provide signature first.");
    } else {
        saveSignature(signaturePad.toDataURL());
    }
});

function saveSignature(dataURL) {
$.ajax({
  type: "POST",
  url: "script.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 
});
}

PHP, "script.php":

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/');
    $img = $_POST['img'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
?>

Upvotes: 0

Views: 1150

Answers (1)

Yashar Aliabbasi
Yashar Aliabbasi

Reputation: 2719

In PHP code you must get $_POST['imgBase64'] instead of $_POST['img'].

your PHP code dosen't return json data

try this: echo json_encode(['result' => $success ? $file : 'Unable to save the file.'])

Upvotes: 1

Related Questions