'How to export or download csv file using ajax?
I have a problem with my code downloading csv file. I can get the data but i can't download the csv file. Here is my ajax code:
// Export
$('#export_csv').click(function(){
var checkbox = $('.checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"csv_action.php",
method:"POST",
data:{action:'export_csv'},
dataType:'json',
success:function(data)
{
$("#select_all").prop('checked', false);
$('#message').html(data);
setTimeout(function(){
$('#message').html('');
}, 5000);
}
});
}
else
{
alert("Please select at least one records");
}
});
Here is my php file code: The output for this code is the data that i fetch from the database and the data of the student i selected from data table. I tried several methods changing the data type is response and function(success)
// Export CSV
if($_POST["action"] == 'export_csv')
{
$filename = 'reports.csv';
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
{
$object->query = "
SELECT * FROM tbl_student WHERE
s_scholar_stat = ''
";
$object->execute();
$result = $object->get_result();
$content = array();
$title = array("Student ID", "First Name", "Middle Initial", "Last Name", "Date of Birth", "Account Status");
foreach ($result as $rows) {
$row = array();
$row[] = $rows["ss_id"];
$row[] = $rows["sfname"];
$row[] = $rows["smname"];
$row[] = $rows["slname"];
$row[] = $rows["sdbirth"];
$row[] = $rows["s_account_status"];
$content[] = $row;
}
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}
fclose($output);
echo '<div class="alert alert-success">Selected Student Data Exported in CSV
Successfully</div>';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
