无法在服务器上将HTML5 Canvas另存为Image

I know that a similar question has been asked before but none of them helped me. up vote

I have written some JavaScript that allows the user to draw on the canvas in different colors and pen sizes. I want to upload the canvas to my server

This is my index.html:

    <html>
  <head>
  </head>
  <body>
     <canvas id="canvas"></canvas>
     <button id="button_clear" onclick="test()">Clear/upload canvas</button>

<script>
function test(){
var canvas  = document.getElementById("canvas");
var dataURL = canvas.toDataURL();
$.ajax({
  type: "POST",
  url: "script.php",
  data: {
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved');
});
}
</script>

script.php:

<?php
    // requires php5
    //define('UPLOAD_DIR', 'FBdraw/');
    $img = $_POST['imgBase64'];
    $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.';

?>

When I refresh the script.php page it saves a empty 0 kB image.