0

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

SupGen
  • 195
  • 17

1 Answers1

0

You could use the FormData object to mock a HTML form, and then post this. This will result in the file being available in PHP's $_FILES.

var pdf = doc.output('blob');

var formData = new FormData();
formData.append('data', pdf);

$.ajax({
    url: jspod.ajax_url + '?action=so56917978_upload',
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

atymic
  • 3,093
  • 1
  • 13
  • 26
  • thank you for your answer. I am now getting a different error. I am getting admin-ajax.php 413 error code. Apparently this means that the data sent is too large for the server. is there any way that I can compact the data? – SupGen Jul 21 '19 at 15:13
  • I am unsure why there would be a 413 error with a PDF file as it shouldnt be too large. Is there any way you know of to compact the file on transfer so that it is of minimal size? – SupGen Jul 21 '19 at 20:02
  • You should be able to fix that error by raising the PHP post limit: https://stackoverflow.com/questions/2184513/change-the-maximum-upload-file-size – atymic Jul 21 '19 at 21:32
  • Ive tried, Ive raised it to 100M but still no joy. It appears to be server related. A PDF shouldnt take much memory though which puzzles me. if for example it was 3mb (max) thats not overly big and shouldnt give that error – SupGen Jul 21 '19 at 21:39
  • What we server are you running? Can you check it's config? – atymic Jul 21 '19 at 21:40
  • I am on a shared server through 1&1 ionos. but I am able to upload pics etc to the back end so I would assume that a PDF should be of the same size. Which makes me think that the file being saved is a lot bigger than it should be – SupGen Jul 21 '19 at 21:47
  • Can you check the network tab in chrome to see the request size? – atymic Jul 21 '19 at 21:57
  • It says 532B which I also find odd. Id expect it to be a few kb – SupGen Jul 21 '19 at 22:04
  • How large is the PDF? – atymic Jul 21 '19 at 22:14
  • Not sure, I've checked different ones that I have made and downloaded rather than saving and they range from 150kb to 2.1mb. They have been made using slightly different code but there are large differences in size – SupGen Jul 22 '19 at 08:01
  • I have just changed the out put to `var pdf = doc.output('blob');` I am now back to getting a `200` responce but `No Data Sent` with blob I am getting form Data - Data:(binary). Which I am assuming now means that I need to change the PHP to decode binary. So I changed it to: `$data = base_convert($_POST['data']);` with no joy – SupGen Jul 22 '19 at 18:37
  • Incase you our anyone else fancies a look I've created a test page - www.easyfreight.co.uk/pod – SupGen Jul 22 '19 at 22:00
  • I have added an update to my question. I feel as though I am making progress although could be false hope lol – SupGen Jul 23 '19 at 19:00