1

I need to download files via ajax request success. I wrote ajax code as written below. Processing the ajax request in controller. It send the data. But, I saw as an alert. I put disposition also. It converts but can't able to download.

Can anyone help me to solve this problem?

Ajax :

email_download_file = function(id, email) {
    if(id !== null){
        $('#customButton').attr('disabled','disabled');
        var jqxhr = $.post('/orders/csv/download', {
            email: email,
            emaillist_type: $('#emaillist_type').val(),
            nrecords: $('#no_of_records_selected').val()
        }).done(function(data) {
            alert(data);
        }).fail(function() {
            $('#customButton').removeAttr('disabled');
            alert("There was a problem with us receiving your data. Please refresh this page and try again. Or contact us at support@onegoodemail.org. We're sorry this happened! :(");
        }).always(function() {
        });
    }
}

controller:

def order_download
        begin
            email = params[:email]
            emaillist_type = params[:emaillist_type]
            num_records = params[:nrecords]
            email_records = EmailList.where(emaillist_type: emaillist_type).limit(num_records.to_i)
            send_data email_records.to_csv, type: "text/csv; charset=iso-8859-1; header=present", disposition: "attachment;filename=#{emaillist_type}.csv"
        rescue Exception => e
            render :nothing, status: 401
        end
    end

model:

def self.to_csv
        CSV.generate do |csv|
            csv << ["First Name","Last Name","Designation","Email","Industry","Company Name","Website","City","Country"]
            all.each do |l|
                csv << [l.firstname,l.lastname,l.designation,l.email,l.industry,l.company_name,l.website,l.city,l.country]
            end
        end
    end

1 Answers1

2

I'm afraid you can't download a file via ajax. For this you should try to perform separate request.

Try sending the params as a form submission (because your action controller expects the POST request). Maybe something like this in your view?

<form action="/orders/csv/download" target="_blank">
    <input type="hidden" name="email" value="..." />
    <input type="hidden" name="emaillist_type" value="..." />
    <input type="hidden" name="nrecords" value="..." />
</form>

Did you notice that I used target="_blank" in form tag? This might make an impression, that the request has been performed asynchronously, which is far from effect your trying to achieve, but this is something you can start with!

If you really want to stick to AJAX like downloading file, maybe this is something you could give a try? (https://stackoverflow.com/a/9970672/4381282 - PS. I haven't tried that on my own, but it seems reasonable!) I'm not sure if it supports POST requests, though.

Good luck!

Community
  • 1
  • 1
Paweł Dawczak
  • 9,519
  • 2
  • 24
  • 37