Using AJAX to send a PDF created with jsPDF to server.
When I run the script and use Inspect > Network
and check admin-ajax.php
I se at the bottom Request Payload [object object]
From my research, as far as I can tell this means that something is being sent to the server but it cannot decode it so I get > No Data Sent
I cannot see anything wrong with my code but if someone can help to debug, that would be great
The code I have used:
JS:
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas){
console.log("#pdfsubmit clicked");
var img = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'pt', 'a4' );
doc.addImage(img, 'JPEG', 20, 20);
var pdf = btoa(doc.output());
$.post({
url: jspod.ajax_url+'?action=so56917978_upload',
contentType: false,
processData: false,
data:{
data: pdf
},
/*dataType: 'json',*/
success: function(response, status) {
alert(response);
}
});
}
});
}
functions.php - register Script:
function ajaz_scripts() {
wp_register_script('js-pod', get_stylesheet_directory_uri() . '/js/POD.js', array('jquery'),'1.1', true);
wp_enqueue_script('js-pod');
wp_localize_script( 'js-pod', 'jspod', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'admin_enqueue_scripts', 'ajax_scripts' );
PHP Script:
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload_callback' );
add_action( 'wp_ajax_nopriv_so56917978_upload', 'so56917978_upload_callback' );
function so56917978_upload_callback() {
if ( ! empty( $_POST['data'] ) ) {
$data = base64_decode($_POST['data']);
file_put_contents( get_stylesheet_directory_uri() . '/POD/pod.pdf' , $data );
echo "success";
} else{
echo "No Data Sent";
}
echo 'got there';
die();
}
If anyone could advise as to how to sort the [object object], it would be much appreciated
UPDATE
I have changed my JS to:
function make_product_sheet() {
console.log("#pdfsubmit clicked");
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML(document.getElementById("product_sheet"), function() {
var file = btoa(pdf.output());
var formData = new FormData();
formData.append('data', file);
$.ajax({
url: jspod.ajax_url+'?action=so56917978_upload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
}
And I got a success message. I then checked the folder that the PDF should have been sent to and nothing is there...
I checked the NEtwork tab of inspect element and at the bottom - formData
it looked to be an extremely long base64 text string.
I have no idea what to do from here, my php should decode the base64 and save bit it looks asthough it has done neither