Sending to server using Ajax is giving /admin-ajax.php 400 error
-
I am running on a shared server and as a result, do not have root access to the server.
I am using jsPDF to convert a submitted form from HTML to PDF. This works great and there is no issues when downloading on client-side to their browser.I have been trying to use Ajax, however, to save the PDF to a selected folder in my directory but keep getting the error
POST https://website.co.uk/wp-admin/admin-ajax.php 400I have submitted my code on stackoverflow and no one can tell me where I have gone wrong so hopefully I’ll have more joy here 🙂Firstly, In functions.php I have added:
function ASAP_scripts() { /** All of my other scripts are also registered here**/ 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( 'wp_enqueue_scripts', 'ASAP_scripts' );Also in functions.php:
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"; } die(); }The JS used:
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 = doc.output('blob'); $.ajax({ url: jspod.ajax_url, type: 'post', contentType: false, processData: false, data:{ data: pdf, action:'so56917978_upload', }, dataType: 'json', }); } }); }I have tried different things with the above JS such as:
changing dataType to ‘Text’
contentType to ‘application/json charset=utf-8’As well as countless others. I would really appreciate if someone could advise as to where I have went wrong.
The topic ‘Sending to server using Ajax is giving /admin-ajax.php 400 error’ is closed to new replies.