Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST to server, receive PDF, deliver to user w/ jQuery

I have a link that the user clicks to get a PDF. In jQuery, I create a POST ajax call to the server to get the PDF. The PDF comes to me with the correct content headers etc that would normally cause the browser to open the Reader plugin, or allow the user to save the PDF.

Since I am getting the PDF w/ an ajax call, I'm not sure what to do with the data that I get in the OnSuccess callback. How can I give the data I receive to the browser and allow it to do its default thing with the PDF response?

like image 722
bryanvick Avatar asked Feb 02 '10 18:02

bryanvick


2 Answers

Take a look at - jQuery Plugin for Requesting Ajax-like File Downloads

The whole plugin is just about 30 lines of code (including comments).

The call is fairly similar to jquery ajax call.

$.download('/export.php','filename=myPDF&format=pdf&content=' + pdfData ); 

Ofcourse, you have to set the content-type and Content-Disposition headers on the server side as you would for any such download.

In java I would do something like this

response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename="exported.pdf"); 
like image 53
Vinodh Ramasubramanian Avatar answered Sep 26 '22 10:09

Vinodh Ramasubramanian


You don't need jQuery at all. Just submit your POST via a form normally, and on the server side, add the HTTP header

Content-Disposition: attachment; filename="whatever.pdf" 

The browser will do its default thing.

Alternately, if you want to be more careful about reporting any errors that might occur during the PDF generation, you can do this. POST your parameters to your server with jQuery. On the server, generate the binary content and cache it somewhere for a few minutes, accessible via a key that you put in the user's session, and return a "success" Ajax response to your page (or if there was an error, return an "error" response). If the page gets back a success response, it can immediately do something like:

window.location = "/get/my/pdf"; 

The server then returns the cached PDF content. Be sure to include the Content-Disposition header, as above.

like image 22
Sean Avatar answered Sep 25 '22 10:09

Sean