2

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)
DeeBee
  • 145
  • 11
  • Possible duplicate of [Download File Using Javascript/jQuery](http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery) – Slava.K Feb 12 '17 at 12:08
  • Probably this answer will help http://stackoverflow.com/a/23013574/7362128 – Slava.K Feb 12 '17 at 12:09

1 Answers1

1

Maybe it's better to make a redirect:

window.open("plan/goal_designer_spreadsheet.xls", "_blank");
Victor Castro
  • 267
  • 4
  • 10
  • The route from routes.rb: get 'plan/goal_designer_spreadsheet'. I made your changes re: not sending the format and got the same result: I get a render complete message in the log, but no downloaded file. – DeeBee Feb 12 '17 at 20:08
  • Thanks Victor. This worked great. I just had to remove the "plan/" and pass parameters at the end of the string: `url_string = "goal_designer_spreadsheet.xls?sb="+start_balance`, `window.open(url_string, "_blank");` – DeeBee Feb 14 '17 at 20:46
  • Note these lines were instead of the entire $.ajax call I had at the start. – DeeBee Feb 14 '17 at 20:50
  • Great, I'm glad to help. – Victor Castro Feb 15 '17 at 02:59
  • @DeeBee Accept the answer if it helped you – Abhi Oct 01 '21 at 16:03