D
D
Doniyor Mamatkulov2017-06-15 13:39:08
JavaScript
Doniyor Mamatkulov, 2017-06-15 13:39:08

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);
    }

But if you access the method through Ajax, the file is generated but not downloaded. Here is the jquery:
$("#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

1 answer(s)
M
Maxim Timofeev, 2017-06-15
@doniyorbekm

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 question

Ask a Question

731 491 924 answers to any question