Save jsPDF to serve With jQuery,Ajax and PHP

I have written a jQuery function using jsPDF to convert a form to PDF, I have then added an ajax command with the intention of saving the generated PDF to the server.

However, when I click submit, the page appears to be completing an action. but, when I look at console I see:

PDFSubmit Clicked

Then

No Data Sent

This, I think, suggests that the Ajax call is working but there is something either in the JS that is wrong or the PHP has a slight error.

My code:

PHP:

add_action( ‘wp_ajax_so56917978_upload’, ‘so56917978_upload’ );
add_action( ‘wp_ajax_nopriv_so56917978_upload’, ‘so56917978_upload’ );
function so56917978_upload() {
if ( ! empty( $_POST[‘action’] ) ) {
$data = base64_decode($_POST[‘action’]);
file_put_contents( get_template_directory() . ‘/POD/pod.pdf’ , $data );
echo “success”;
} else {
echo “No Data Sent”;
}

die();
}

I have tried 2 different JS files, both with the same Result…

JS-1

function sendToServer() {
html2canvas(document.getElementById(“product_sheet”), {
onrendered: function(canvas)
{
console.log(“#pdfsubmit clicked”);

function html() {
var img = canvas.toDataURL(“image/png”);
var doc = new jsPDF(‘p’, ‘pt’, ‘a4’ );
doc.addImage(img, ‘JPEG’, 20, 20);

var pdf = doc.output(‘blob’);
$.ajax({
url: jspod.ajax_url,
type: ‘post’,
async: false,
contentType: ‘application/json; charset=utf-8′,
data:{
data: pdf
action:’so56917978_upload’
},
dataType: ‘json’
});
}
});
}
}

JS-2

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 file = doc.output(‘blob’);
var pdf = new FormData();
pdf.append(‘action’, ‘so56917978_upload’);
$.ajax({
url: jspod.ajax_url,
data: pdf,
dataType: ‘text’,
processData: false,
contentType: false,
type: ‘POST’,
}).done(function (data) {
console.log(data);
});
}
});
}

Any help with figuring out where I am going wrong would be great

Read more here:: Save jsPDF to serve With jQuery,Ajax and PHP

Leave a Reply

Your email address will not be published. Required fields are marked *