2

i am having problem in downloading a CSV file using codeigniter, i want when user press the export button file should start downloading but what happens is response is generated in ajax called function as shown in screen shot. I know i am missing some thing small but i can not get my head straight over it what to do.

AJAX RESPONSE SHOWN IN FIREFOX CONSOLE

AJAX RESPONSE

HTML BUTTON

 <button id="exportData" name="exportData" class="btn btn-primary btn-lg" >Download CSV</button>

AJAX CALL

$(document).on('click','#exportData',function(e){
e.preventDefault();

var jawad = $( ".jawad" ).serialize();
$.ajax({
url         : '<?=base_url();?>command/getReport',
type        : 'POST',
data        :  {str:jawad,procName:$('#procName').val()}
});

});

PHP FUNCTION:

function getReport()
{ 
 //removing above lines as not necessary

$jawad =  $query->result_array();

//pass it to db utility function
$new_report = $this->dbutil->csv_from_result($query);

$this->load->helper('download');
force_download('csv_file.csv', $new_report);
}
jawadxiv
  • 59
  • 1
  • 11

2 Answers2

0

To download the the CSV file post the value using AJAX.

Basic Code:

function getReport(){ 
    $FileName = date("d-m-y") . '.csv';
    $Content = "#ID, Mobile No \n";
    $Content .= "01, 0175162678 \n";
    $Content .= "02, 0165162678 \n";

    header('Content-Type: application/csv'); 
    header('Content-Disposition: attachment; filename="' . $FileName . '"'); 
    echo $Content;
}
anik4e
  • 493
  • 8
  • 16
-1

Try this

$.ajax({
        url : '<?=base_url();?>command/getReport',
        type: 'POST',
        data:  {str:jawad,procName:$('#procName').val()}
      }).done(function($results) {
        document.location.href = '<?php echo site_url('command/getReport');?>';
      });
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 22 '22 at 10:38