使用PHP Error 500在服务器上保存.toDataURL()

I have this function from a GitHub repo that outputs a drawn signature on canvas to a DataURL(). When I inspect it, it comes back as a string of encoded data(a .png).

The user clicks the save button and this happens:

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

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

Then it triggers a PHP script in the same folder, called script.php.

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

I can't find out why it's causing a 500 server error.

The console isn't printing 'unable to save file', nor 'saved.'

You have error in script.php you are receving data in $img while write using $data so need to replace variable

<?php
    // requires php5
    define('UPLOAD_DIR', 'images');
    $img = $_POST['imgBase64'];
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $img); //<---- change here
    print $success ? $file : 'Unable to save the file.';
?>