I have a Rails 3 app which when a download link is clicked on the client an ajax request is made to the server to dynamically generate a file and send it back. The server tells me the file is being sent:
Sent data test.csv (1.4ms)
but the browser isn’t prompting me to download the file. When I inspect the ajax request I see the data coming back in the response. Any help getting the browser to prompt the user to download the file would be appreciated. Below is my code:
Here’s my controller:
def generate_file
list = List.find(params[:id])
file = ''
list.contacts.all.each do |contact|
file << contact.firstname + ',' + contact.lastname + '\n'
end
send_data file, :filename => list.name + '.csv', :type => 'text/csv'
end
Here’s my client side code:
$j('.download').click(function() {
var id = $j(this).attr("id");
$j.ajax({
type: "POST",
url: "/lists/" + id + "/generate_file"
});
});
Here’s my routes.rb
resources :contacts
resources :lists do
member do
post 'generate_file'
end
end
Sending files over ajax doesn’t work as easily as you might hope. You’re probably better off not using ajax and just using a regular HTTP request unless it’s important to use ajax for some reason.
There is a good answer to a similar question here: How do you invoke a file download with link_to_remote in rails?