Reputation: 15
I can easily export data as excel file with a simple code but I get a problem when I need to call the export.php by j query code. Data is not downloaded as export.php file. The code is :
<?php
include '../../config.php';
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv<span>; charset=UTF-16LE</span>");
$out = fopen("php://output", 'w');
$flag = false;
$result = mysql_query("SELECT * FROM employee") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
if($row['photo']!='')
{
$row['photo']="http://localhost/admin/employee_image/".$row['photo'];
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
Is there any way to call this file by jquery?
Upvotes: 0
Views: 201
Reputation: 906
No you cannot do this by Javascript using jQuery or any other library, AJAX calls data in Javascript engine inside the browser.
But you can use HTML5 download attribute:
<a href="your_file.xls" download="YourFile.xls">Download Excel</a>
And give proper headers in PHP:
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=your_file.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
EDIT:
Although the above will work, I take my words back as I found this:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
Made by https://stackoverflow.com/users/455556/john-culviner , ask him for help if you need
Cheers!
Upvotes: 1