'PHP function call from AJAX - download file
I am trying to use AJAX & PHP Function for downloading a file. my goal is to use AJAX for sending variables from Datatable to PHP function. and PHP function will search for the file in my storage and download it.
It's not working. when I using the URL I can download the file. but when I trigger it with AJAX it's not working.
I want to create a PHP function that will receive file name and generate the download link for an HTML button. (which displayed in a data table)
Ajax:
//download button
$('#files').on('click', 'button#download',function (ref) {
var data = table.row($(this).parents('tr')).data();
var file_name=data.filename;
ref.preventDefault();
// alert(data.filename);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
datatype:'binary',
url: "/download?"+data.filename,
success: function(result){
console.log(result);
}
});
});
PHP:
public function getDownload(){
$tmpfile='1520001503b1.png';
$sd= DB::table('files')
->where('filename',$tmpfile)
->get();
$myFile = public_path("uploads/1520001503b1.png");
$headers = ['Content-Type: application/png'];
$newName = 'bla'.time().'.png';
return response()->download($myFile, $newName, $headers);
}
route:
Route::match(['get', 'post'], '/download','FilesController@getDownload');
Solution 1:[1]
as far as I know You can't download the files from a direct ajax request instead you could return a dynamic download url to the ajax response and just trigger browser location change as below in ajax success function.
location.href = 'download.php';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fayis003 |
