0

How can I download using force_download php in ajax, Is it possible ???

I have an ajax request like this :

function save(path, namaFile, namaExcel) {
    $.ajax({
        url: "<?php echo site_url('members/program_kecil/program_kecil/convert_csv_ke_excel'); ?>",
        type: 'post',
        data: {path: path,
            nama: namaFile,
            namaExcel: namaExcel
        },
        success: function (response) {
            $('#modal_form').modal('hide'); // show bootstrap modal
        }
    });
}

This is the php :

class Program_kecil extends Members_Controller{
public function convert_csv_ke_excel() {
    require_once APPPATH . "/libraries/CSVToExcelConverter.php";
    $this->load->helper('file');
    $this->load->helper('download');

    CSVToExcelConverter::convert($this->input->post('path'), $this->input->post('namaExcel'));
    $this->download_excel($this->input->post('namaExcel'));
    echo json_encode($this->input->post('namaExcel'));
}

public function download_excel($file) {
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename=' . $file);
    $filedownload = file_get_contents($file);
    force_download($filedownload, null);
}

I just got my modal is closed;

P.S : in success ajax (callback) like this:

"D:\/xampp\/htdocs\/develop_tsurumaru\/assets\/uploads\/LJTD2508.xlsx"

Which is the path of excel will be downloaded.

Please advise.

Fadly Dzil
  • 2,154
  • 3
  • 34
  • 85
  • Possible duplicate of [Using jQuery and iFrame to Download a File](http://stackoverflow.com/questions/16799483/using-jquery-and-iframe-to-download-a-file) – cske Aug 23 '16 at 11:35

1 Answers1

1

Through AJAX you can't download file directly, You will need to open that path in new tab to download it.

Like this,

window.open('http://YOUR_HOST/develop_tsurumaru/assets/uploads/LJTD2508.xlsx', '_blank');

Update the URL to access the file from web instead of file system.

Alok Patel
  • 7,842
  • 5
  • 31
  • 47