Im tryng to generate a basic csv file with some data. When I use and alert inside the ajax call it will show me the data, but when I click the button it will not generate an CSV file. Im new to yii2 so im still learning.
//view export/index.php
<div class="modal-button-row">
<a href="#" id="export-trigger" class="btn btn-success pull-left">Export</a>
</div>
<script>
function runExport() {
jQuery.ajax({
type: "POST",
url: "<?php echo yii\helpers\Url::to(['cms-export/ajax']) ?>",
success: function (test) {
alert(test);
},
error: function (exception) {
alert(exception);
}
});
}
</script>
<?php
$js = <<<JS
jQuery(document).ready(function ($) {
$("#export-trigger").click(function (e) {
runExport();
e.preventDefault();
});
});
JS;
$this->registerJs($js);
?>
//model
public function generateCsv(){
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = [datacomeshere];
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
fputcsv($fp, $line, ';');
}
fclose($fp);
}
//controller
public function actionAjax()
{
Export::generateCsv();
}