0

I've implemented the ajax download CSV functionality, for that I've used below code. But it's not working. The code is working fine if I use it in plain PHP code but when I use it in AJAX code, the file is not downloading but it's returning values.

Return Data

bla_col1, bla_col2, bla_col3
data1, data2, data3



Ajax Code

$.ajax({
        url: base_url + "/product/download-csv",
        type: 'get',
        data: {category: category},            
        success: function (response) {},
        error: function (err) {},
        complete: function (result) { 

        }
    });

Laravel / PHP Code

$filename = "my-file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
fputcsv($fp, $csvHeadings);
foreach ($csvValues as $csvValue) {
    fputcsv($fp, $csvValue);
}
KRY
  • 103
  • 1
  • 2
  • 9
  • why you want to use here ajax at all? – Itsmeromka Nov 29 '17 at 11:27
  • 1
    thats the nature of ajax.. what you can do is to save the csv as a file on the server, and return the url to your ajax function - create a hidden link - inject this in the dom and trigger a click event – Atural Nov 29 '17 at 11:27
  • @Salman When I run that URL the file is getting downloaded – KRY Nov 29 '17 at 11:29
  • 1
    Well, you can't use AJAx here. s. https://stackoverflow.com/a/8771353/3179423 – dev0 Nov 29 '17 at 11:32
  • You can't trigger a download with a Ajax request. Your download code also looks wrong. This topic might help you https://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request – Raymond Nijland Nov 29 '17 at 11:33
  • @Salman I didn't get this, which html part I need to add? – KRY Nov 29 '17 at 11:33
  • Could try [changing it to application type download](https://stackoverflow.com/a/23540193/1624318); it should offer the user a dialog asking if they would like to download it or not. – HB- Nov 29 '17 at 11:35

0 Answers0