Using AJAX and PHP to output PDF

6.4k views Asked by At

The way my web app is supposed to work is that the user fills out a form and then the AJAX sends the form data to a PHP file that generates a PDF (using xpdf). Then the generated PDF should be available for download on the HTML page with the AJAX.

If I open pdf.php directly in the browser it works fine. However I need to figure out how to connect it with the AJAX so that it sends the generated PDF back to the AJAX and the user can simply click a button on the page to download it.

AJAX:

$.ajax({
    url: 'pdf.php',
    type: 'POST',
    data: pdfData
})
.done(function(response){
});

pdf.php:

<?php 
include('fpdf.php');
include('fpdi.php'); 

// initiate FPDI 
$pdf =& new FPDI(); 
// add a page 
$pdf->AddPage();
...
$pdf->Output('address.pdf', 'D'); 
?>
2

There are 2 answers

0
Drk_alien On

After your pdf file is done, you know the path and all details for the pdf. Return an html or an json object back to your page, and create a new html button that will link to the pdf file.

Your returned data will contain all needed details about the pdf. Name, path, etc...

0
Darien On

You need a two step process, you can't do it just with just the first AJAX call.

  1. Your AJAX call shouldn't return the PDF contents, it should return an URL to access the PDF instead, like /path/to/getpdf.php?id=23535&securitykey=142505
  2. Your javascript should attempt to open that new URL in a new window or tab
  3. Your getpdf.php script should serve the PDF data with the appropriate HTTP Content-Type and Content-Disposition headers to force a download-prompt.

Most browsers will close the new tab automatically after the user chooses to open/save the file.