<a style="margin:0px 10px;" href="<?php echo base_url(); ?>admin/download_members" class="btn btn-info" ><i class="glyphicon glyphicon-cloud-download"></i> Download Excel</a>
when I click on above anchor tag my excel download perfectly. I need to download excel with some filter. and I am using AJAX to download but not able to download.
my ajax
$(document).ready(function(){
$("#download_excel").click(function(){
var state = $("#state").val();
var city = $("#city").val();
$.post("<?php echo base_url()?>admin/download_members",
{
state:state,city:city
},
function(response){
});
});
});
my controller
function download_members(){
$state = $this->input->post('state');
$city = $this->input->post('city');
$data['members'] = $this->Select->view_members_to_download($state,$city,$status);
$this->load->view('admin/spreadsheet_view',$data);
}
my model
public function view_members_to_download($state,$city){
if($state){
$this->db->where('u.state',$state);
}
if($city){
$this->db->where('u.city',$city);
}
$this->db->order_by('u.plan','asc');
$this->db->from('users u');
$this->db->join('states s', 'u.state=s.id', 'left');
$this->db->join('cities c', 'u.city=c.id', 'left');
$this->db->join('packages p', 'p.package_id=u.plan', 'left');
$this->db->join('profile_type pt', 'pt.profile_type_id=u.profile_type', 'left');
$query = $this->db->get();
return $query->result();
}
You can use download helper in your controller
function download_members(){
$this->load->helper('download');
$state = $this->input->post('state');
$city = $this->input->post('city');
$data['members'] = $this->Select->view_members_to_download($state,$city,$status);
$list = $data['members'];
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output');
$name = 'member.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
}