I have a form_tag that generates a pdf and serves it to the user. The final send_data is like :
send_data pdf.render, type: 'application/pdf', :filename => filename, :compress => true
This works fine with a standar form, but it does not work when i try to use ajax to set :remote => true.
The ultimate thing i want to do is use :disable_with to disable the button while the pdf is generating.
Any ideas on how i could fix this ?
OK, you have to use the various AJAX callbacks.
Assume you have a link on your page to generate the PDF.
<%= link_to 'Generate PDF', '/generate_pdf', :id=>'genpdf', :remote=>true %>
Now you have to bind events to the 'genpdf' element created by the above. i.e.
$('#genpdf').bind('ajax:beforesend', disablepdf)
$('#genpdf').bind('ajax:complete', enablepdf)
Then define the two javascript functions declared above to manipulate the HTML element as needed.
var disablepdf = function() { $("#genpdf").removeAttr("disabled") };
var enablepdf = function() { $("#genpdf").attr("disabled", "disabled") };
I know is is an old thread but I thought I'd let you know how I got this to work in case anyone else finds there way here as I did.
The problem with using ajax for the request is that the response (the pdf file) is next to impossible to handle and then serve to the user as a file so don't bother. Instead I used rails built in caching to get the pdf served after generation.
Once you have the link working "conventionally" add the :remote => true, :disable_with => 'loading...'
to your link to ajaxify it.
Set config.action_controller.perform_caching = true
in your config > enviroments > development.rb so you can see this working before pushing to production =p.
Use Action Caching on your download action and set an appropriate expiration if required i.e. caches_action :download, :expires_in => 5.minutes
at the top of your controller.
This means that when you click on your link it will send the ajax request, generate the pdf and return the page. Now the page is cached so if you click the link again the request will take milliseconds not seconds. Next all we need to do is a little javascript to download the pdf once its ready.
However you do your javascript (unobtrusively or not) add the following:
$("#download_link").on('ajax:success', function(){
document.location = $(this).attr("href")
});
This will get the browser to follow the link as if the :remote => true
wasn't there once the ajax request is successful (i.e. the pdf is generated). Because the response has been cached it'll download immediately.