In my Yii2 application i'm dynamically generating .zip files that i want to download through an Ajax call in one of my views.
This is my code
_view.php
$js = <<<JS
$('#button-download').on('click', function(){
var tkn = $('meta[name="csrf-token"]').attr("content");
var fields = JSON.stringify($('#gridview').yiiGridView('getSelectedRows'));
$.ajax({
url: '$urlDownload', // Generated with Url::toRoute([someaction]);
type: 'get',
dataType: 'json',
data: {
field: fields,
_csrf : tkn,
},
success: function(data){
console.log(data);
// ?
// ?
// ?
}
});
});
JS;
$this->registerJs($js);
This is my view file, here i register the $.ajax method that reach an action in my controller.
Controller.php
/**
* Download Action
*
* @param integer $field
* @return mixed
*/
public function actionDownload($field) {
if (Yii::$app->request->isAjax && !empty(json_decode($field))) {
// Bring some Data From Db
// Create a new Zip
$archive = new \ZipArchive();
$now = $timestamp; // let's assume that the $now variable is a valid timestamp
$zip_name = Yii::t('app', 'NameThisArchive').$now.'.zip';
if (!$archive->open(Yii::getAlias('@app/runtime/foo').'/'.$zip_name, \ZipArchive::CREATE)) {
throw new \Exception('Can\'t create the file');
}
foreach ($datafromdb as $record) {
if ($somecondiction) {
// Generating files and adding them to my archive
$archive->addFile($path, '/'.Yii::t('app', 'somefileinpdf{0}.pdf', [$record->id]));
}
}
$archive->close();
// return ?
// Yii::$app->response->sendFile($path, $zip_name);
}
}
In this controller i receive the data from the ajax request. I'm able to create the zip archive and save it to my runtime folder.
Now, the problem, is how can i send this file to the ajax call. (in the .success() callback).
What should i return ?
Looking in the yii official forum i've found some response helper:
Yii::$app->response->sendFile("path", "Filename");
If I return that function return Yii::$app->response->sendFile("path", "Filename");
No file is download in my browser. But looking in my Safari browser console i see that a xhr request (the one i send with ajax) return some data.
So a response is given. How can i capture it with my Ajax function?
Thanks for any help.