Send PDF to browser after ajax call

I have a php script that is called through an ajax call. Values ​​are sent to this script to build pdf. I want to send a PDF to a browser, but since the script that creates the PDF returns to the page using javascript, I don’t see how to do it. Any ideas?

+4
source share
4 answers

I would recommend a little different. Instead of calling AJAX, redirect to the following URL:

./path_to_pdf_script/script.php?param1=val1&param2=val2 

This script will be the one that generated the pdf. Place somewhere on top of the script of this header:

 header('Content-type: application/pdf'); 

And just the echo line where the pdf file is located. If you want the user to download this pdf instead of viewing, you could make an AJAX call using the found example HERE :

from php.net

If you want the user to be asked to save the data that you are sending, for example, the generated PDF file, you can use the "Content-Disposition header to provide the recommended file name and force the browser to display a save dialog.

 <?php // We'll be outputting a PDF header('Content-type: application/pdf'); // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="downloaded.pdf"'); // The PDF source is in original.pdf readfile('original.pdf'); ?> 
+2
source

You can use iframe instead of ajax request and force download pdf file.

+2
source

As you noticed, your AJAX call cannot directly output the PDF to the browser. One solution is to remove AJAX and send the user directly to the page that creates the PDF file. This approach is very common and well documented. But there is a way to use AJAX to create a PDF file so that the user stays on the web page until the file is ready.

Your AJAX call can answer using a JSON object with two exclusive fields:

  • "pdfurl" if the PDF file was successfully created and written to disk,
  • "errormsg" if an error occurred.

Something like (in PHP):

 <?php //... if (writepdf($filename, ...)) { $result = array('pdfurl' => '/files/' . $filename); } else { $result = array('errormsg' => 'Error!'); } echo json_encode($result); 

Then the javascript page may contain (jQuery example):

 $.ajax({ type: "GET", url: "ajaxcreatepdf.php", data: {userid: 1}, dataType: "json", success: function(data, textStatus) { if (data.pdfurl) { window.location.href = data.pdfurl; } else { $("#messagebox").html(data.errormsg); } } }); 
+1
source

Ajax request is not directly visible to the user, so redirecting does not make sense

You need to load this PDF file into an existing or new browser window after ajax returns.

0
source

Source: https://habr.com/ru/post/1403308/


All Articles