Retrieve values at the same time as file attachment download - php

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;
}
});

Related

How to pass only text part of html code `(excluding the tags)` to php page using get method from ajax

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;
}
?>

WordPress - Export table as csv using jQuery/Ajax

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;

How to use php readfile code to open PDF file in new tab (wysiwyg)

I'm using following code to open a PDF document from database. My problem is
the PDF document is opened in the current tab but I want it to open in a new tab instead.
$query = "SELECT name, type, size, content FROM files WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: inline; filename=$name");
echo $content;
I'm using redactor wysiwyg to add the PDF. Let me know if you need more info, thank you.
Solved my problem to open the PDF in new tab. We can't open new tab by using php code. Only can do it by adding the "target="_blank" in redactor.js
Following is part of the code from redactor WYSIWYG. You can found the "target="_blank" inside the code.
fileUploadCallback: function(json)
{
var data = $.parseJSON(json);
var text = $('#redactor_filename').val();
if (text == '') text = data.filename;
var link = '' + text + '';
// chrome fix
if ($.browser.webkit && !!window.chrome) link = link + ' ';
if ($.browser.msie)
{
if (text != '') $(this.doc.getElementById('span' + this.spanid)).replaceWith(a);
else $(this.doc.getElementById('span' + this.spanid)).after(link).remove();
this.syncCode();
}
else this.execCommand('inserthtml', link);
// file upload callback
if (typeof this.opts.fileUploadCallback == 'function')
{
this.opts.fileUploadCallback(this, data);
}
this.modalClose();
},
For more information, please get the code from redactor WYSIWYG website.

PHP : Second Function not being called

I am using PHP and want to run 2 functions, one after the other.
These functions are getallmydata() and createCSV()
The code below runs the first function fine but the second function createCSV() is not working. It seems like it is not being called properly.
Is there anything wrong with the structure of my code as both functions work correctly independently? I cannot work this out!
<?php
//run this function//
getallmydata();
//then run this function//
createCSV();
function getallmydata(){
require_once dirname(__FILE__).'/cm/csrest_general.php';
require_once dirname(__FILE__).'/cm/csrest_clients.php';
require_once dirname(__FILE__).'/cm/csrest_campaigns.php';
$api_key = 'MY API KEY';
$wrap = new CS_REST_General($api_key);
$result = $wrap->get_clients();
$Content = "";
if ($result->was_successful()) {
foreach ($result->response as $client) {
$client_wrapper = new CS_REST_Clients($client->ClientID, $api_key);
$client_details_result = $client_wrapper->get();
$campaigns_result = $client_wrapper->get_campaigns();
if ($client_details_result->was_successful()) {
/* This is where the client details will be */
$client_details = $client_details_result->response;
echo ('<pre>');
/*print out the company name*/
echo "Company Name = " . $client_details->BasicDetails->CompanyName . "<br/>";
/*print out the company markup*/
echo "Markup On Delivery = " . $client_details->BillingDetails->MarkupOnDelivery . "<br/>";
$count = 0;
if ($campaigns_result->was_successful()) {
/*print out the latest campaign name of the current campaign*/
foreach ($campaigns_result->response as $campaign_ob) {
echo 'Latest Campaign Name = ' . $campaign_ob->Name . '<br/>';
//echo 'Latest Subject = ' . $campaign_ob->Subject . '<br/>';
//echo 'Total Recipients = ' . $campaign_ob->TotalRecipients . '<br/>';
//echo 'Sent Date = ' . $campaign_ob->SentDate . '<br/>';
/*Set content for CSV File*/
//$Content .= "This is within the loop \n";
$count++;
if($count > 0) break;
}/*end loop*/
}/*end campaigns if statement*/
echo ('</pre>');
} else {
echo 'Failed with code '.$client_details_result->http_status_code."\n<br /><pre>";
var_dump($client_details_result->response);
}
}
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo ('</pre>');
}
} //end main function
/*create the downloadable csv file*/
function createCSV(){
$FileName = date("d-m-y") . '.csv';
# Titlte of the CSV
//$Content = "Company_Name Markup Campaign_Name Subject Recipients Date \n";
# fill data in the CSV
//$Content .= "\"John Doe\",\"New York, USA\",15,65465464 \n";
$Content .= "Testing The Function Works OK \n";
//$Content .= "This should be another line";
header('Content-Type: application/csv');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}//end csv download function
/*end create downloadable .csv file */
?>
I think you should get the error: headers already sent. (you checked that the second function is called right? You can find it out by placing a echo on the first line of the function.)
You are trying to create a CSV page but you are parsing HTML in the first function, so the header is already sent to the client saying that it is a normal HTML page. Remove these echo's in the first function and it should work.
Quote of the PHP manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
More info about headers: PHP header
First think I would tell you is
1 you should first write function definition and then you should call a function
i.e
function getallmydata(){
// function code
}
function createCSV(){
// function code
}
getallmydata();
createCSV();
2 . The second thing is that check that is there any white space left in the code out side php code or any o/p that is sent as resonse as because when ever you user header() at that if any kind of content other than header() is sent as response then header() function fails. Try this things and check again.

javascript return function's data as a file

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.

Categories