Convert database query results to excel and allow download from ajax call - php

I have looked through a few similar questions but can't quite find what I am looking for (please don't mark this as duplicate as I did try to find an answer without posting a question)
When the user clicks on a button, an ajax request is sent to the controller where I am getting data back from the model. I am then converting it to a csv format and on success of the ajax call I want the file to download. I have everything working except the download part. I have seen some examples where you just redirect but that doesn't download anything, it shows a new page with the results.
$( '.spExcel' ).on('click', function() {
$.ajax({
url: url + '/Widgets/exportSpExcel',
type: 'POST',
})
.done(function (data) {
window.location.assign(data);
})
});
PHP:
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$results = $this->DashboardModel->listPeople();
$filename = 'People_' . date('dmY') . '.csv';
header("Content-Description: File Transfer");
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$handle = fopen('php://output', 'w');
$header = array("Name", "Contact Number");
fputcsv($handle, $header);
foreach ($results as $result):
fputcsv($handle, $result);
endforeach;
fclose($handle);
}

Ajax isn't capable of writing a downloaded file - the browser has to do that itself. You could use window.open() but that would open the file in a new tab or window, which would then close immediately. That can look messy - it works but isn't ideal.
The simplest way to deal with this is to make the link download the response directly, without trying to use Ajax. Change the link to suit your needs, but it would be something like this...
<a href="/Widgets/exportSpExcel" class="spExcel" download>click to download</a>
Just add the download attribute to a link. It really is that simple :)

Related

PHP headers are not working in WordPress ajax call

I have a PHP script that generate and download CSV file. Following is the code of that script:
<?php
$cars = array(
array("Volvo",22,1888),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles' ));
//Loop through the array and add to the csv
foreach ($cars as $row) {
fputcsv($output, $row);
}
exit;
?>
This script work fine when I access it directly, But my aim is to use this script in a WordPress AJAX call, I have created the AJAX using WordPress AJAX API as following:
add_action( 'wp_ajax_export_timeline', 'export_timeline' );
And then same PHP code (that is pasted above) is written in callback function export_timeline, but instead of generating CSV and downloading against the AJAX call, printed array is returned in response. There is no error in AJAX in call, I have tested with echoing other string, its responding fine.
But in case of upper mentioned script, I think PHP headers are not working in callback function, because instead of generating and downloading CSV, its echoing the array in response. Any help is appriciated.
To my knowledge PHP headers do not work with AJAX calls:
what you can do is create csv data in your php code and echo that as a response to your callback.
Your php code must return a json as
echo json_encode(['data' => $data, 'status' => 'success' ]);
$data variable must have valid CSV formatted data.
In your javascript you can use the following for CSV download:
function download_csv(){
var make_download = (function () {
var $a = $('<a>', {
'class': 'csv-downloader',
'style': 'display: none'
});
$('body').find('.csv-downloader').remove();
$('body').append($a);
return function (data, fileName) {
const blob = new Blob([data], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
$a[0].href = url;
$a[0].download = fileName;
$a[0].click();
window.URL.revokeObjectURL(url);
};
}());
$.when($.ajax({
dataType: 'json',
method: 'POST',
url: URL, // url here
})).then((response) => {
if (response.status == 'success') {
make_download(response.data, `my-file.csv`);
}
})
}
Try to directly call the url, without an ajax call, then it should work.
Try to modify headers as below
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=csvfile.csv" );
header("Content-Transfer-Encoding: binary");

php download save file

$filename = "members.csv";
if($_POST['SaveFileButton'] != ""){
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$filename");
header ("Content-Length: " . filesize("$filename"));
$fp = fopen("$filename", "r");
fpassthru($fp);}
Sometimes this works perfectly and downloads the file.
Sometimes it displays the entire file contents at the top of the webpage, as though I had used echo, followed by the normal webpage underneath it.
I can't figure out why it's printing it to the screen.
The only unusual thing I've changed in this php file lately was adding an OnUpdate event to my Select ListBox.
<script type="text/javascript">
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
var editcode = document.getElementById("codeid").value;
var filter = document.getElementById("filterid").value;
document.location.href="/php/members.php?fullname="+fullname+"&filter="+filter+"&editcode="+editcode;}
</script>

Display message before creating excel in jquery and PHP

I am creating a web app in my company. The user can click on a button and an csv is created with MySQL data.
So far so god.
In jquery, when the user clicks the button it redirect to:
document.location.href = '/SDR/SDRJSON.php?type=' + id;
On PHP the csv file is created:
I connect to the database and create a the csv file:
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row, ';');
}
$FileName = 'PEW_'.$CountryCode;
fclose($fp);
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename='".$FileName."'.csv");
header("Pragma: public");
header("Expires: 0");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
readfile('file.csv');
On the page where the button is, the user clicks there and the page starts waiting for the server and then the csv file starts downloading.
For small files is ok, because it is instantaneous. But for larger files it takes like 10 / 15 seconds. Is it possible to show a message while the page waits for the server?
I don't Think PHP can echo while the csv is being made ... What you could do is split the "Document Formation" and "Document Download" into two parts.
Let Ajax Make a query for the CSV to be made . And when that has been completed the PHP (Document Formation) will echo the Path of the File.
Then After that You can use document.location.href to Newly Created File.
I ll give the code
ajax-code
$('#sample-button').click(function(){
$.ajax({
url : '/SDR/SDRJSON.php?type=' + id,
success : function(data){
if(data.url)
{
var urlToDownload = data.url;
alert("File is ready for download");
document.location.href = "http://www.domain.com/file/path/"+data.url;
// Make sure data.url has the full path or append the data.url
// with some strings to make sure the full path is reflected
// into document.location.href ...
}
else
{
alert("Something went wrong");
}
}
});
alert("CSV is being prepared Please wait... ");
});
documentFormation.php
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$FileName = 'PEW_'.$CountryCode;
$fp = fopen($FileName, 'w');
foreach ($csv as $row) {
fputcsv($fp, $row, ';');
}
fclose($fp);
$response = array();
$response['url'] = $FileName;
echo json_encode($response); // You can handle rest of the cases where to display errors (if you have any)
// Your DocumentFormation PHP Ends here. No need for header() or readFile.
If you dont want the file to stay on server , Edit the document href to This PHP passing 'path' as the parameter
document.location.href = "documentDownload.php?path="+data.url;
documentDownload.php
$path = $_GET['path'];
$filename = end(explode("/" , $path));
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
//Assuming $filename is like 'xyz.csv'
header("Content-Disposition: attachment; filename='".$filename);
header("Pragma: public");
header("Expires: 0");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
// Reading file contents
readfile('Relative Path to File'.$path);
// Deleting after Read
unlink('Relative Path to File'.$path); // To Delete right after reading

javascript : send file to php script for user to download

In the website I'm building, I'm trying to provide users the ability to export and download data in KML format. I've built a PHP script to generate a kml file from a string. It works reasonably well, until requests get too long and then I get 414 errors.
The thing is, I'm pretty sure I'm going at this the wrong way (I'm new to php). Rather than sending my data as a string, which can get to multiple tens of thousands of characters long, I should be sending a file generated by javascript to the php script which would send it back to the user or something like this. Is it possible?
If not, what other options do I have?
Here's my php script :
if($_SERVER['REQUEST_METHOD']=='POST') {
$text = $_POST['text'];
$text = str_replace('\r\n', PHP_EOL, $text);
$text = str_replace('\n', PHP_EOL, $text);
$text = str_replace('\t', "\t", $text);
$text = str_replace('_HASH_', "#", $text);
$filename = $_POST['filename'];
$tmpName = tempnam(sys_get_temp_dir(), $filename);
$file = fopen($tmpName, 'w');
fwrite($file, $text);
fclose($file);
header('Content-Description: File Transfer');
header("Content-Type: application/octet-stream");
//header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename=' . $filename . '.kml');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpName));
ob_clean();
flush();
readfile($tmpName);
unlink($tmpName);
exit;
}
* EDIT *
Ok, I changed the php script to use POST instead of GET which should clear up the length issue. But this has shown me another problem.
I'm using dojo to write my website. I'm doing an xhr request with POST method. This request comes back successfully. In the success handler, I'm navigating to the same url I passed to the request by setting the src of a hidden iFrame (so as to avoid reloading the page). The results in a GET request which doesn't work with my script (POST).Furthermore, I believe this means I'm running the php script twice which makes no sense.
Should I just navigate directly to the url of the php script with required parameters? In this case, how do I navigate to a url using a POST request?
I'm a bit confused about all of this, it probably shows too!
Thanks,
* SOLUTION *
mguimard sent me on the right track to solve my issue. Here's the bit of code I used to send my POST request while avoiding to realod the page:
download: function(text) {
var ifr = document.createElement('iframe');
ifr.setAttribute('name', "target");
ifr.style.display = 'none';
document.body.appendChild(ifr);
var f = document.createElement('form');
f.setAttribute('method',"post");
f.setAttribute('action',"saveFileAs.php");
f.setAttribute('target',"target");
addField(f, "filename", "myFileName");
addField(f, "text", text);
f.submit();
ifr.onload = cleanUp;
function cleanUp(){
document.body.removeChild(ifr);
ifr = null;
}
function addField(form, name, value) {
var i = document.createElement("input");
i.setAttribute('name',name);
i.setAttribute('type','text');
i.value = value;
form.appendChild(i);
}
}
Ggilmann

Force Download via Ajax and PHP

i want to create a downloadscript which allows Force Download of JPGs.
This is my php script:
<?php
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: image/jpg");
header('Content-Disposition: attachment; filename="'.basename($GET['a']).'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize(($GET['a']));
readfile(($GET['a']);
?>
This is a code segment of my js code:
function downloadFile(a){
document.location = "download.php?a="+ a;
}
With this code sample nothing happens. If i append the result into a HTML-tag, it shows the content of the file.
Any ideas how to teach the browser to download this file?
EDIT: SCRIPT UPDATE
You can't download files with ajax. So, if you have something that should happen on ajax, you should return url in response and apply it like document.location = "url"to start download process.
One note here. As I remember, browser will block file download if it is initiated not by user click. So, this will work fine:
.click(function(){
document.location = "download url"
})
But if it is started not by user click, it will be blocked. So, code like this:
.click(function(){
$.ajax({...,
success:function(download_url_from_server){
document.location = download_url_from_server;
}});
})
will be blocked by browser. So, if you want to pass some data with a post, you may submit a form into hidden iframe or to blank page using <form target="...":
function checkToken(token){
var $form = $("#downloadForm");
if ($form.length == 0) {
$form = $("<form>").attr({ "target": "_blank", "id": "downloadForm", "method": "POST", "action": "script.php" }).hide();
$("body").append($form);
}
$form.find("input").remove();
var args = { a: "checkToken", b: token }
for (var field in args) {
$form.append($("<input>").attr({"value":args[field], "name":field}));
}
$form.submit();
}
And in script.php you need to execute code from download.php immediately, if token is Ok, or do a redirect to download script:
header("Location: download.php?a=" . $filename)
Setting the mime type to image/jpeg will most probably not work. So, you need application/octet-stream instead to force the download.
Replace the content type header in your php with the following:
header('Content-Type: application/octet-stream');
Also, One nice solution instead of using document.location is to inject an iframe. Use the following function in your success callback
function downloadFile(url)
{
var iframe;
iframe = document.getElementById("download-container");
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = "download-container";
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
}
iframe.src = url;
}
It seems you have errors in your script.
First of all, correct speliing for GET variable is $_GET['a'], not $GET['a'].
The second issue here is that you have extra opening parenthesis, when I copied your code, I received 500 Internal Server Error response.
If we correct mistakes, it seems to work fine.
Just try corrected version of your code.
<?php
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: image/jpg");
header('Content-Disposition: attachment; filename="'.basename($_GET['a']).'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($_GET['a']));
readfile($_GET['a']);
?>
You're getting it confused a bit. As FAngel pointed out, you can't download files via AJAX. What you need to do is redirect the user to another page that then has your above PHP code in it. That PHP code should then allow the user to download the file directly. What you're attempting is absolutely possible, you just need to approach it from another direction, ie not with AJAX.
You can force download file with Mouse middle event:
const url = "https://www.google.com.vn/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png";
const forceDownload = url => {
try {
const link = document.createElement('a');
const fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
const event = new MouseEvent( "click", { "button": 1, "which": 1 });
link.href = url;
link.download = fileName;
link.dispatchEvent(event);
} catch(e) {
document.location = url;
}
}
forceDownload(url);

Categories