I'm writing a website that generates some PDF documents for users. I need to do two things.
1) When the user clicks submit, the generated PDF, which is returned in the POST response, should be opened in a new tab.
2) For some requests, the original page needs to be refreshed to show that this PDF is in the user's library.
I've come up with this JS. It does submit the form properly, puts the output in a new tab, and reloads the page.
$.ajax({
type: 'POST',
url: '/share/pdf/',
data: $('#pdf_share_form').serialize(),
async: false,
success: function (d) {
var w = window.open();
w.document.write(d);
location.replace('/pdf/');
}
});
The problem is that document.write() is expecting HTML, so a PDF shows up as a jumble of binary characters.
I feel like I need to indicate that the data should be downloaded when writing it, but I'm not sure how to go about that. Note that some generated files are ephemeral and immediately deleted after being returned from the form POST, so I can't do any sort of window.open(url).