Hey i am using canvas to put an image out and save it. I can not get wordpress to make an ajax request. I keep getting back 0 responseText. I have beeen working on this for days and can’t seem to get it to work. My page is http://studio-42.com/games.
jQuery( document ).on( 'click', '.draw-game', function() {
var testCanvas = document.getElementById("mycanvas");
var canvasData = testCanvas.toDataURL("image/png");
var postData = "canvasData="+canvasData;
var debugConsole= document.getElementById("debugConsole");
debugConsole.value=canvasData;
jQuery.ajax({
url : drawing.ajax_url,
type : 'post',
data : {
action : 'save_the_drawing',
imgBase64: postData,
},
success : function( response ) {
alert(response);
Here is my JS
And this one is the PHP code
add_action( 'wp_enqueue_scripts', 'drawing_game_enqueue_scripts' );
function drawing_game_enqueue_scripts() {
if( is_page('games') ) {
wp_enqueue_style( 'drawing-game', plugins_url( '/drawing-game.css', __FILE__ ) );
}
wp_enqueue_script( 'drawing-game', plugins_url( '/drawing-game.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'drawing-game', 'drawing', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_ajax_nopriv_save_the_drawing', 'save_the_drawing' );
add_action( 'wp_ajax_save_the_drawing', 'save_the_drawing' );
function save_the_drawing() {
$img = $_POST['postData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);
}
I keep only getting back a 0 and its driving me crazy! Please Help. Thanks!
You need to call
die()
at the end of your script. Simply returning or echoing will not suffice.WordPress by default returns 0 as a return code (0 being no errors detected) if you do not specify a return value (by calling
die()
)Here’s some additional details, and there’s more in the WP Codex: https://wordpress.org/support/topic/ajax-call-returns-0