0

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).

fandingo
  • 1,330
  • 5
  • 21
  • 31
  • 2
    is there a reason you are submitting this with ajax and not a regular form submit in a new tab? – Ramy Nasr Jul 30 '14 at 16:40
  • I think http://stackoverflow.com/questions/9840230/how-to-display-a-pdf-stream-in-a-browser-using-javascript might help you out. – Mahesh Guruswamy Jul 30 '14 at 16:53
  • 1
    @Ramy, I needed to be able to specify `async: false` to be able to open the new tab, read data, and then do the page reload. Thanks to your suggestion, I was able to find `$.when()`, and came up with a solution that works great. – fandingo Jul 30 '14 at 17:02
  • Glad I - indirectly - helped. As a rule of thumb: if you decide to use `async: false` for an ajax call, there is usually a better way of doing things. :) – Ramy Nasr Jul 30 '14 at 17:21

1 Answers1

0

Thanks to @Remy I thought a little more about what I needed to do. Before I wrote this question, I actually had a standard jQuery submit() call with the form set as target="_blank". That worked fine, but I was having problems with reloading the page after the submit. That led me to $.ajax(), which was the wrong solution.

The solution was quite simple:

$.when($('#pdf_share_form').submit()).then(function() {
    location.replace('/pdf/');
});


<form id="pdf_share_form" action="/share/pdf/" target="_blank" method="post">
    <input id="pdf_index" name="pdf_index">
    <input id="pdf_name" name="pdf_name">
</form>
fandingo
  • 1,330
  • 5
  • 21
  • 31