Reputation: 1786
I have written a snippet in which an image is saved using ajax and php.
Here is the code,
Ajax:
$jq("#up").click(function() {
var canvasData = upcan.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testsave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
});
Here up is the button that is clicked. canvasData has canvas context data in image format.
Php:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$random_digit=rand(0000,9999);
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'canvas/canvas'.$random_digit.'.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
The image is saved successfully.Now i want to get the name of the saved image in ajax so that i can save it in a variable and use it for further. So how can I do that?
Upvotes: 0
Views: 400
Reputation: 8990
// js
ajax.onreadystatechange = function() {
alert(ajax.responseText);
}
// php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
//...
echo 'canvas/canvas'.$random_digit.'.png';
}
But in my opinion it is better to use jQuery ajax and its events.
Upvotes: 2