POV
POV

Reputation: 12005

How to download Excel file by Ajax in Laravel?

I use this library to export Excel

I send POST request to endpoint, where method retrieves data and creates file:

return Excel::download(new EventsExport($request), $filename);

Problem is that I get this file as binary in response, and browser does not start download it.

How to fix it?

Upvotes: 0

Views: 8077

Answers (5)

Henry
Henry

Reputation: 11

$.ajax({
     type : 'GET',
     url : '/download-excel',
     success:function(){
         window.location.href = '/download-excel';
     }
});

Upvotes: 1

Francesco Taioli
Francesco Taioli

Reputation: 2866

after some struggling, here the simplest solution i found

Your controller

return Excel::download(new EventsExport($request), $filename, null, [\Maatwebsite\Excel\Excel::XLS] );

Your frontend

 var data = match=3&win=false; //example
 var url = "{{route($routeForYourExcel)}}?" + data;
 window.open(url, '_blank');

Hope it help

Upvotes: 1

iamawesome
iamawesome

Reputation: 662

I don't know anything about angular, but if you are in laravel you can,

call a ajax request to your controller

then create a temporary excel file with your data.

then simply download it via this header.

header('Content-Type: text/csv'); echo file_get_contents('your_file_location_url');

then unlink your temp file if you want to

Upvotes: 1

Ap Koponen
Ap Koponen

Reputation: 475

If you are making the request as an AJAX request from your SPA the download won't start. You need to either make the endpoint accept GET-requests and link the user to that URL or embed a form to you SPA app that will do a normal POST to the endpoint.

Upvotes: 1

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

I think proper way is to store it on your server and send link to your ajax request:

return response()->json([
    'url' => 'url-to-stored-file'
]);

And in AJAX response you can do:

function(data) {
    window.location.href = data.url;
}

I know this is not preferable way to do it but it works

Upvotes: 0

Related Questions