javascript – Using AJAX and PHP to output PDF-ThrowExceptions

Exception or error:

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.


    url: 'pdf.php',
    type: 'POST',
    data: pdfData



// initiate FPDI 
$pdf =& new FPDI(); 
// add a page 
$pdf->Output('address.pdf', 'D'); 
How to solve:

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…


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.

Leave a Reply

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