Over the last couple of days I have learnt about the canvas-element and now I want to add AJAX to save the canvas to the server. Specifically, I am letting users draw on the canvas and when they are finished they click a button and the canvas is sent and saved to the server. The code below works excellently.
Javascript:
var testCanvas = document.getElementById('imageView');
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=callback();
ajax.open("POST",'script.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send("canvasData"+canvasData );
function callback (){alert ('it works!');}
PHP-code:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen( 'images/'.uniqid().'.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
echo "saved";
}
else{
echo "no raw data";
}
?>
However, I would like to have the filename and location returned to the script, so that I can present the server-side image and location to the user. I have not adjusted the php-code yet, because using the following returns an empty string:
function callback () { alert (ajax.responseText);}
I have searched and the topic seems to have been addressed a couple of times without resulting in me being able to fix the above.
Where I am going wrong?