i am doing an ajax call and called a php page which is extracting data from a mysql table and need to convert it to excel and need to store in server folder only.
Now the problem is while doing the ajax call, its going to that php page and returning to the main page without creating the excel file.
But when i tested the php page directly then its creating the excel file and downloading it. But why its not working via ajax call.
This is my ajax call from previous page --
$.ajax({
type: "POST",
url: "admin-advertiser-details-exports.php?selectedColumns="+selectedColumns+"&excelColumn="+excelColumn,
contentType:false,
processData:false,
success:function(data){
alert('Export done');
}
});
And this is my php page which is exporting to excel --
<?php
session_start();
include 'db.php';
if(!isset($_SESSION))
{
$uname=$_SESSION['uname'];
}
else if(empty($_SESSION['uname']))
{
header('Location: index.php',TRUE);
}
$UserName = $_SESSION['uname'];
$UserID = $_SESSION['uid'];
$UserType = $_SESSION['utype'];
$selectedColumns = $_GET['selectedColumns'];
$excelColumn = $_GET['excelColumn'];
$array = explode('\t',$excelColumn);
$sql = "select ".$selectedColumns." from advertisers_details ad join user_details ud on ad.adv_manager=ud.user_id order by ad.adv_id asc";
$setRec = mysqli_query($linkID1, $sql);
$columnHeader = '';
foreach ($array as $value) {
$value = '"' . $value . '"' . "\t";
$columnHeader .= $value;
}
$setData = '';
while ($rec = mysqli_fetch_row($setRec))
{
$rowData = '';
foreach ($rec as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=advertiser_detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
If i am running this php page directly the i am getting the excel file, but via ajax call its not working.
responseJavascript variable, not as a file on the client's computer, and that is a prison from which it cannot easily escape. If you want to trigger a download via Javascript, better to do a window.location or window.open command to the URL which prompts the download.