2

I can't figure out how to "catch" the event (if it exists) when my Rails app is done sending a file with the send_data method:

# view
= link_to 'Download!', download_path

# controller
def download
  # some logic
  send_data csv_data, filename: 'export.csv'
end

I would like to catch the event when my server is done sending the CSV file to the client in order to hide a loading.gif image which is shown right when you click on the download link (there is nothing related to AJAX here, to be clear).

Any help would be appreciated, thanks!

(Ruby 1.9.3, Rails 3.2.13)

Similar question (using cookie): Browser event when downloaded file is saved to disk


update:

I tried to listen on the events of my link, but no event at all is shown:

monitorEvents(document.body.querySelectorAll('a#export_link'));
Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117

1 Answers1

0

I think it would be easier if you send the data with jQuery and AJAX

$('button').on('click', function(){
  $.post(url, {data}, success: function() { alert("DONE!"); 
  });
});
pauloancheta
  • 349
  • 2
  • 9
  • I know it would be great here, but I can't send a file in response to a JS request (javascript security rule) (http://stackoverflow.com/questions/16242359/how-to-trigger-download-with-rails-send-data-from-ajax-post) – MrYoshiji Apr 02 '15 at 19:04
  • 1
    How about using a callback? `after_save :do_this, only: [:download]` – pauloancheta Apr 02 '15 at 19:10
  • It is a good start but I am not modifying data at all. Im just exporting a huge list of priced_items which is generated when we click on the download link (your example was mixing model callbacks like `after_save` with controller callback like `before_filter`) – MrYoshiji Apr 02 '15 at 19:17
  • I tried a version of what you suggested: `before_filter :send_csv_file, only: :export` but I can see in my server's log "Filter chain halted as :export rendered or redirected" – MrYoshiji Apr 02 '15 at 19:34
  • `before_filter` would not work since that code will run BEFORE your download code runs. maybe try `after_commit`. – pauloancheta Apr 02 '15 at 19:37
  • `after_commit` is an ActiveRecord callback. I am not triggering any AR event at all in my "CSV generation" process – MrYoshiji Apr 02 '15 at 19:39
  • I'm sorry I wouldnt be of any help anymore. The only solution I could think of is putting another fuction after `send data...` that triggers an event. But that might not work either. – pauloancheta Apr 02 '15 at 19:42