I am trying to trigger an excelsheet download via a javascript call. When I use a button link_to to call the rails action, it works fine. But when I call the rails action via js script (which I want to do) I get the same rendered message in the log but the excel does not download. I presume this is something to do with the ajax/background task call but I can't figure it out. Any idea how to get the javascript approach to work?
Rails Action:
def goal_designer_spreadsheet
@format = params[:format]
logger.debug "\nformat = #{@format} \n"
respond_to do |format|
format.html
xls_filename = "Excel_file__abc.xls"
format.xls {headers["Content-Disposition"] = "attachment; filename=\"#{xls_filename}\"" }
end
end
2 buttons: 1 triggers a JS call (not working), one direct to rails (working):
<button class="btn btn-primary" id="goal_download_list">Download this Plan (.xls) javascript</button>
<%= link_to "Download this Plan (.xls) rails", plan_goal_designer_spreadsheet_path(format: "xls"), :id => "", :class => "btn btn-small btn-primary" %>
Javascript call:
if ( trigger_object.id.match(/goal_download_list/) ) {
$.ajax({
type: 'get',
url: "/plan/goal_designer_spreadsheet",
data: {
"format": "xls"
},
success: function(data, textStatus) {
}
});
}
Output log: similar in both cases, but in case of JS call, no xls downloads:
Rendered plan/goal_designer_spreadsheet.xls.erb (0.0ms)
Completed 200 OK in 344ms (Views: 339.9ms | ActiveRecord: 0.0ms)