2

Hi there Stackoverflow. I am trying to call a PHP script via AJAX that will create and download a CSV file. I know this isn't normally supposed to be done, however I would like to do it this way.

My ajax below returns the csv data as shown by this output:

enter image description here

$.ajax({
    type: "POST",
    url: "<?=site_url('front_office/get_csv/')?>",
    data: {hashed_center_ids : hashed_center_ids, print_data : print_data},
    dataType: "text",
    success: function(response) {
        console.log(response)
        var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
        window.open(uri, 'test.csv');
    }
});

The problem is that using the lines

var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response); window.open(uri, 'test.csv');

does not download the file as a CSV. But rather it give it no extension with the name "download". Does anybody know how can I make it so it downloads with the .csv extension? Thanks.

  • 2
    Let me get this right, you want to post some data to a PHP, that will process it and return a CSV data? And you want that returned data to be automatically offered as a file download? – Emil Borconi Feb 21 '16 at 20:46
  • 2
    If that is the case you should read this post: http://stackoverflow.com/questions/7034754/how-to-set-a-file-name-using-window-open – Emil Borconi Feb 21 '16 at 20:54
  • 1
    `application/csv` isn't a valid mime type. The correct mime type for a csv is `text/csv` – Mark Baker Feb 21 '16 at 20:54
  • It works Mark. Any idea how to change the name? It comes out as "download.csv". –  Feb 21 '16 at 20:58
  • That is correct Emil. –  Feb 21 '16 at 20:58

1 Answers1

1

I can't comment, so: You can change the name of the csv by adding following to the header

 filename=whatever.csv
Klassik
  • 141
  • 11