views:

1261

answers:

4

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

+1  A: 

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
Ron DeVera
We are using AJAX to hide a link during the generation of the CSV, downloading a file without AJAX is not a problem and was already being done by the application, we needed to hide a link to stop users clicking the link more than once.
railsninja
Try using $('#link').click(function(){$(this).hide()});
SeanJA
Obviously that should have been $(this).remove();
SeanJA
+1  A: 

Downloading it isn't the problem; you can download any data you like via XmlHttpRequest. The hard part is parsing it. There are several ways to parse it, from regexs to string indexing.

Ignacio Vazquez-Abrams
A: 

You can use "AJAX" to download anything .. Some people would say you shouldn't call it AJAX in that case since that term is rigorously devoted to downloading XML. But really it's just a mechanism to get data into the client w/o reloading a page. If you were loading HTML it'd be called AHAH, for CSV i guess you'd call it AHAC or AJAC? ..

Scott Evernden
+1  A: 

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.

Luke P M