I have a table with a list of the users, and I want to save multiple records using a checkbox in Codeigniter application, I use jquery ajax to send multiple rows to my controller. On the button click, I would like to get the email of each checked user from the database and save the result in a CSV.

/* My script */

$('#button').click(function(){

    var checkbox = $('.rows_checkbox:checked');
    if(checkbox.length > 0)
    {
        var checkbox_value = [];
        $(checkbox).each(function(){
            checkbox_value.push($(this).val());
        });
        $.ajax({
            url:"<?php echo base_url(); ?>backoffice/candidates/csv_all",
            method:"POST",
            data:{checkbox_value:checkbox_value},
            success:function()
            {
                alert('success');
            }
        })
    }
    else
    {
        alert('Select atleast one records');
    }
});

/* Controller */

public function csv_all()
{

    if($this->input->post('checkbox_value'))
    {
        $file_name = 'student_details_on_'.date('Ymd').'.csv';
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file_name");
        header("Content-Type: application/csv;");

        $id = $this->input->post('checkbox_value');
        for($count = 0; $count < count($id); $count++)
        {
            $student_data = $this->users_model->get_csv($id[$count]);
        }
        // file creation
        $file = fopen('php://output', 'w');

        $header = array("email");
        fputcsv($file, $header);
        foreach ($student_data->result_array() as $key => $value)
        {
            fputcsv($file, $value);
        }
        fclose($file);
        exit;
    }
}

/====== Model ====/

public function get_csv($id)

{
    $this->db->select('email');
    $this->db->where('id', $id);
    $query = $this->db->get('users');
    if ($query->num_rows() > 0) {
        $query_rslt = $query->row_array();
        return $query_rslt['email'];
    }
    else { return FALSE; }
}

when I click the button, I receive the alert but it does not generate the csv file

0 Answers