I am using Ajax functionality to retrieve my content and I need to export PDF on success of jQuery.ajax()
. How can I do that?
If you are retrieving PDF data from your server in your AJAX success and need to output it to your user as a download, it can be accomplished with a tiny bit of base64 encoding. If I understand correctly, you most likely have a scenario where your server is possibly returning a PDF or some other data type on success (like XML). In this case, you have two steps to handle the request:
1) Determine the content type via its header. Here is an example of splitting your handler based on the response:
$.ajax({
type: "POST", url: "/test", data: someData, success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf(‘xml’) > -1) {
// handle xml here
}
if (ct.indexOf(‘pdf’) > -1) {
// handle pdf here
}
}
});
2) Once you have your PDF content, you can redirect the browser to show the pdf by using a base64 data trick. First, encode the data content in base64. There are a number of libraries to help you do this in Javascript. Then, return your content via document.location.href:
document.location.href = 'data:application/pdf;base64,' + base64PDFData;
That should get what you need. You could theoretically forward any content-type to the browser in this method.
EDIT:
I should mention that the data uri will unfortunately not work in IE due to security restrictions.