Answer the question
In order to leave comments, you need to log in
Ajax can't force a file to download?
Good afternoon!
Project in Yii2. I want to generate a csv file and make it download.
If you go to the method through the browser line: the file is generated and even downloaded. Here is the method itself:
public function actionExportStaffCsv() {
//$requestID = htmlspecialchars(trim(Yii::$app->request->get('dept')));
$filepath = $_SERVER["DOCUMENT_ROOT"].'/web/junk/test_'.date('dmYhis').'.csv';
$output = fopen($filepath, 'w+');
fputcsv($output, ["#", "Description", "test", "test2"], ';');
fputcsv($output, ["1","2","3","4"], ';');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.'test.csv');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
}
$("#exportStaffCsv").on('click', function (e) {
e.preventDefault();
//var last_element = getUrlParam();
$.ajax({
url: "/ru/tree/export-staff-csv",
data: {dept: 4},
success: function (resp) {
//alert(resp);
}
});
});
Answer the question
In order to leave comments, you need to log in
In response to ajax, return the url to the file and already in js process the server response, redirecting the user to the received url
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question