Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading CSV via AJAX

Tags:

Can you use AJAX to download a generated csv file from a web application? If so does anyone have any kind of reference that I could be pointed towards?

EDIT: Sorry I should have mentioned I am using Prototype's Ajax.Request and I looked in firebug's response tool and the generated CSV is the response, I just need to get it to pop up with the save file option after has been generated by the Ajax.Request

like image 617
nitecoder Avatar asked Mar 23 '09 04:03

nitecoder


2 Answers

This is a known limitation of Ajax requests, you will need to use JS like:

window.location='download-csv.rb';

Instead of using an Ajax request. Another way is to change the location of a hidden Iframe, but this has it's own pro's/con's.

You will never get an Ajax request to display the 'file save' dialog, no matter what HTTP headers you send.

like image 180
Luke P M Avatar answered Sep 30 '22 15:09

Luke P M


In light of your latest edit, to make your CSV file trigger a file download (instead of rendering in the browser), there's no need for Ajax.

Instead, the solution is to have your back-end system add this HTTP header when the CSV file is requested:

Content-disposition: attachment; filename=<your_filename.csv>;

Your implementation here depends on the back-end system you're using. If you're using Rails (as your username suggests), here's a start:

filename = 'your_filename.csv'
headers['Content-Type'] = 'text/plain'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
render :layout => false
like image 41
Ron DeVera Avatar answered Sep 30 '22 15:09

Ron DeVera