Question:: I am developing a plugin. This plugins creates a custom table in WP database. How can I export the data from this table using Ajax?
Where I am?: I have created the hook and the handler. I can actually grab the data. Please see my code below.
add_action ( 'wp_ajax_nopriv_exportcsv', 'exprot_to_csv' );
add_action ( 'wp_ajax_exportcsv', 'exprot_to_csv' );
<script type="text/javascript">
jQuery("#export-csv").on("click",function(e){
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {"action":"exportcsv"},
success: function(response){alert(response);}
})
});</script>
function exprot_to_csv(){
global $wpdb;
$table_prefix = $wpdb->prefix;
$table = $table_prefix.'my_custom_table';
$result = $wpdb->get_results("SELECT * FROM ".$table."");
foreach ($result as $row) {
$output .="\n";
$output .='"'.$row->post_id.'",';
}
$output .="\n";
$file = "custom_table";
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
echo $output;
exit;
}
In the alert box, I am getting comma separated post IDs as expected. But I am not sure how to move on from here. I mean how to handle this response and prompt the user to save/download the file.
Any help?
You are close...! I ran into same problem, tried a similar solution.
Check this question out:
Download file through an ajax call php
And THIS specific answer:
https://stackoverflow.com/a/11452917
Make sure to look at Dario's answer
Summary -
AJAX is not for streaming downloads.
The solution here is to make an iFrame
Load a PHP file into that iFrame using jQuery
Serve up your file with a File Transfer
'header('Content-Description: File Transfer');'
This works in WordPress. Use Admin-Ajax.
Cheers
Hopefully this will solve your problem.
In jQuery:
window.location = response->in success
Action ajax:
Please remove all headers
echo admin_url($filename);
die;
Related
I want to export the mysql data to excel file through ajax
Ajax code
$('#dateBox').change(function(){
$('#getData').html('loading...');
var date = $('#dateBox').val();
var limit = $('#sortByNo').val();
//set download button attributes
$('#exportSilver').attr('data-date',date);
if(date != ''){
var action = 'getDataFromDate';
$.ajax({
url: 'fetch_payouts.php',
method: 'post',
data: {date:date,action:action,limit:limit},
success:function(data){
$('#getData').html(data);
window.location.href = 'download.php?data='+data+'';
}
});
}
else{
$('#getData').html('');
}
});
download.php file
<?php
if(isset($_GET['data'])){
$data = $_GET['data'];
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=insway.xls");
echo $data;
}
?>
It works but the problem is it also exports the html tags to the excel file and there are two rows in the database table and it only exports one row and two columns from second row
This is the excel file output
You can strip all the tags from the array $_GET['data']
try following code:
$data = array_map(function($v){
return trim(strip_tags($v));
}, $_GET['data']);
Or simply
$data = array_map( 'strip_tags', $_GET['data'] );
You can use strip_tags function of PHP on data before echoing it.
Maybe like this:
$data = array_map(trim(strip_tags($data))
So the new code looks like:
<?php
if(isset($_GET['data'])){
$data = $_GET['data'];
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=insway.xls");
$data = array_map(trim(strip_tags($data));
echo $data;
}
?>
I have a form that triggers a file download:
function downloadEnhancedSubtitle ($subtitle,$totalSequences,$filename) {
// Build string
$subtitleString = '';
foreach ($subtitle as $thisSegmentKey => $segment) {
$sequenceString = $segment->sequence."\r\n";
$sequenceString .= formatMilliseconds($segment->startTimeInMilliseconds).' --> '.formatMilliseconds($segment->endTimeInMilliseconds)."\r\n";
if(isset($segment->textLine1)) $sequenceString .= utf8_decode($segment->textLine1)."\r\n";
if(isset($segment->textLine2)) $sequenceString .= utf8_decode($segment->textLine2)."\r\n";
if(isset($segment->textLine3)) $sequenceString .= utf8_decode($segment->textLine3)."\r\n";
$sequenceString .= "\r\n";
$subtitleString .= $sequenceString;
}
$subtitleString .= ($totalSequences+1)."\r\n99:99:90,000 --> 99:99:99,999\r\nEnhanced\r\n";
// Download string
header("Content-Type: text/plain;charset=windows-1252");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Length: " . strlen($subtitleString));
echo $subtitleString;
}
The user submits a subtitle file and it is "optimized" on the server and sent back to the user as an attachment download. But I would like at the same time (same form view where the file is downloaded) to trigger a modal with some data of the process, for example, how many lines where optimized.
As "Content-Disposition: attachment" automatically downloads everything printed on screen, is there any way I could retrieve the value of a variable using that response? Maybe changing everything to be an ajax request?
(using PHP on the backend)
Firstly you need to save file on server then you can get response with all variables, but it's one problem - you need to delete all generated files for safety.
function downloadEnhancedSubtitle ($subtitle,$totalSequences,$filename)
{
[...]
// Response for ajax
echo json_encode(
[
'filename' => $filename,
'link' => 'http://localhost/uploads/' . $filename,
'subtitle' => $subtitleString
]
);
}
Javascript (jQuery)
You are getting all your variables from server.
$.ajax({
[...],
success: function(response) {
// if response is not object
var obj = JSON.parse(response),
filename = obj.filename,
link = obj.link,
subtitle = obj.subtitle;
// if response is object
var filename = response.filename,
link = response.link,
subtitle = response.subtitle;
}
});
My problem is not being able to encode the image properly after retrieving it from the database otherwise all my work is fine. After I fetch the image I managed to display it at the same php file using "header('content-type: image/jpeg')".
<?php
header('content-type: image/jpeg');
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select image from images order by id desc limit 1";
require_once('connection.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
?>
The previous piece of code is for displaying directly but it was for testing only, I need to use it as a JSON source so I modified it in this way:
header('Content-type: application/json');
.
.
.
$r['a'] = base64_encode( $result['image']);
echo json_encode($r);
For the Jquery and Ajax part also worked fine and I tested it by making another json file and put an image encoded professionally by this website https://www.base64-image.de/.
And here is Jquery code:
$(document).ready(function(){
(function()
{
d='';
var poll=function()
{
$.ajax({
url: "getjson.php",
type :"get",
dataType: "JSON",
success: function(json)
{
d +='data:image/jpeg;base64,';
d +=json.a;
$("#myimg2").attr("src",d);
}
})
};
poll();
setInterval(function(){
poll();
}, 2000);
})();
});
What I need now is to encode the image just like what this website does https://www.base64-image.de/ because this line base64_encode( $result['image']) seems to be not enough, I have tried many solutions available online but no one worked for me!
I have a from that when submit runs a little php to export data to a csv. The php looks like :
$out = '';
if (isset($_POST['csv_hdr'])) {
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_text'])) {
$out .= $_POST['csv_text'];
}
$filename = "z_".date("Y-n-d",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-n-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $out;
exit;
This works fine if I do a normal path to the php file like :
<form name="export" action="http://website.com/getcsv.php" method="post">
I am trying to move this php function into a controller now and call it that way. I am working on a magento admin module so I have to pass the url with the security key. So I move that function into an action in the controller :
public function getcsvAction(){
$out = '';
...
}
Then I am able to get the url with something like :
<?php echo Mage::helper("adminhtml")->getUrl("module/index/getcsv/");?>
This gives me a link with the key like :
http://website.com/module/index/getcsv/key/7431c859914c40d3f66dfcd1530813b3/
If I paste that link into the browser it executes the php fine. However when I replace it in my form action it no longer works and just does a redirect to the dashboard. I can not see any errors output and I am not sure what is happening. Any ideas on how to get this POST to work using a secure path as the action?
I found it thanks to this post.
I needed to add this to the form :
<input type="hidden" name="form_key" value="<? echo $this->getFormKey(); ?>" />
Your URL is missing the adminhtml area. Try this:
Mage::helper("adminhtml")->getUrl("*/module/index/getcsv/");
I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.