Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send_data for csv file returns text of file, not file

Good day! I want to download autogenerated file qwerty.csv, but it returns only text "12345" (without file). Can you help me?

UI

<script type="text/javascript">
function getCsv() {
    var ids = getSelectedRecordIds();
    $.post('/payments/form_csv.csv', { ids: ids }, function(data) {});
}
</script>

Controller

def form_csv
    csv_string = CSV.generate do |csv|
        csv << ["12345"]
    end

    respond_to do |format|
        format.csv {
            send_data csv_string, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=qwerty.csv", :filename => "qwerty.csv"
        }
    end
end

In console

Started POST "/payments/form_csv.csv" for 127.0.0.1 at 2012-06-18 18:18:11 +0400 
Processing by PaymentsController#form_csv as CSV
  Parameters: {"ids"=>["18\n\t  "]}
  Rendered text template (0.0ms)
Sent data qwerty.csv (0.4ms)
Completed 200 OK in 2ms (Views: 0.4ms | ActiveRecord: 0.0ms)

But there are no file prompt...

like image 257
AnDragFag Avatar asked Jun 18 '12 14:06

AnDragFag


1 Answers

Ow, it works without ajax, as a form submit!

There is same problem in this topic: http://www.ruby-forum.com/topic/111107

Make the form a non-AJAX form I try it… And it works!

Controller

def form_csv
    csv = get_csv
    send_csv(csv)
end

def get_csv
    result = CSV.generate do |csv|
        csv << ["12345"]
    end
    return result
end

def send_csv(csv)
    send_data csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => 'attachment; filename=payments.csv'
end

UI

function getCsv() {
    var ids = getSelectedRecordIds();
    params = {ids: ids}
    post_to_url("/payments/form_csv", params);
}

where post_to_url - is method from JavaScript post request like a form submit topic.

And after all

protect_from_forgery :except => :form_csv

in controller to disable authentication token for pay_csv request.

Ugly decision, but it helps me… May be is there more right way?

Viren, I'll try it, thanks!

like image 138
AnDragFag Avatar answered Oct 22 '22 13:10

AnDragFag