简体   繁体   中英

How to download a pdf using ajax and TCPDF

My code works fine when I run the php script without ajax as a GET request. I get prompted to download the rendered pdf and all is well. However, I need to use ajax because I need to send more info from an html page to the php script than can be handled in a GET request.

What do I need to put into my ajax to make this work?

Thanks

js

function makePDF()
{
var x;
if(window.event) // IE8 and earlier
    {
    x=event.keyCode;
    }
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
    {
    x=event.which;
    }
keychar=String.fromCharCode(x);

alert(keychar);

if (keychar == 'p' || keychar == 'P')
{
    var charSheetHTML = characterSheet.innerHTML;

    $.ajax({ 
     url: 'pdf.php',
     data: {'charactersheet': charSheetHTML,},
     type: 'post',
     success: function (data) {**WHAT_DO_I_PUT_HERE??**},
     error: function (data) { alert("error\n" + data.toString()); }
    });
}
}

pdf.php

<?php
include_once( "bxcharacter/PDFChar.php.inc" );
PDFChar();  
?>

PDFChar.hph.inc

<?php

require_once('./tcpdf/tcpdf.php');

function PDFChar(){


 $pdf = new TCPDF();


 $pdf->AddPage('P');
 $pdf->writeHTML($_POST['charactersheet']);


 $pdf->Output("character.pdf", 'D');


}

?>

This is not an ajax solution, but you can send your data with this way and if no error occurs, your page will not change.

Create a form element with inputs hidden which contains your data you want to send:

example format:

<form id="myForm" method="GET" action="pdf.php">
   <input type="hidden" name="data1" type="hidden" value="your JSON.stringify() data">
</form>

js code (call these where your ajax request is):

var myForm =  '<form id="myForm" method="GET" action="pdf.php">';
    myForm += '<input type="hidden" name="data1" type="hidden" value="JSON.stringify() data">';
    myForm += '</form>';

$("body").append(myForm);   // temporarily appending 
$("#myData-form").submit(); // submitting form with data
$("#myData-form").remove(); // remove form after submit

And as you said, force download will force file to download and page will remain same. However, if an error occurs, your page will change of course.

I don't know whether this is an effective way or not but in my case, this does the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM