Download excel table via ajax - php

Im trying to download an excel file using a post request.. i was wondering if this could only be done using some sort of a hidden iframe or maybe using flash as i have read in some post however im not sure how to do this. This is the code i have so far..
employeeExcel.php
<?php
require_once ("../models/employeesModel.php");
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=reporteEmpleados.xls");
$employees = new Employee();
$emp = $employees->search_empleados();
?>
<html>
<body>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
<th>Tipo Doc.</th>
<th>Email</th>
</tr>
</thead>
<?php
foreach ($emp as $datos) {
$id = $datos["id_employee"];
$image = $datos["image"];
$name = $datos["employee_name"];
$surname = $datos["employee_surname"];
$dni = $datos["dni"];
$email = $datos["email"];
?>
<tbody>
<tr id="<?php echo $id; ?>">
<td> <?php echo $name; ?></td>
<td> <?php echo $surname; ?></td>
<td> <?php echo $dni; ?></td>
<td> <?php echo $email; ?></td>
</tr>
</tbody>
<?php
}
?>
</table>
<button onclick="employeeExcel();
return false" name="export">Export</button></a>
Here is where i do the ajax post
function employeeExcel() {
var uri = "employees.php";
$.ajax({
url: uri,
type: 'POST',
data: datos,
success: function() {
window.location = uri;
}
});
}

The file is not empty, but just in the wrong format.
HTML marks for tables (<tr><td>...) are not recognized as Excel file syntax. You need to create a real Excel file to use extension .xls of the output file.
For example, try to rename the file extension of the downloaded file with .txt instead of .xls and open it. You will see the HTML table output, which is not Excel syntax.
Have a look on this excellent PHP library to generate Excel file http://phpexcel.codeplex.com/

Related

How to fetch id of selected chebox and export selected record as CSV using Codeigniter()?

I am not able to get how I can fetch the ids to export the records.
I have a dropdown button which contains three options (import, export and create new user). Once I click on the export button, the records where the checkbox is selected should be exported as a CSV file.
How the button looks like:
I have code for exporting a CSV file, but I am not able to fetch the ids of the checkboxes.
Export CSV file code (working fine):
public function export_csv($param = '')
{
$filename = strtotime("now"). ".csv";
$delimiter = ",";
// Create a file pointer
$f = fopen('php://memory', 'w');
// Set column headers
$fields = array('Id', 'Name', 'Email', 'Phone', 'Created', 'Status');
fputcsv($f, $fields, $delimiter);
$lineData = array(1,'34',$param,'859685968','29-09-2019','online');
fputcsv($f, $lineData, $delimiter);
// Move back to beginning of file
fseek($f, 0);
ob_clean();
// Set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// Output all remaining data on a file pointer
fpassthru($f);
// Exit from file
exit();
}
HTML table will be looking like:
<table class="table">
<thead>
<tr>
<th style="width: 2%;"><input type="checkbox" name="select_all" id="select_check" class="checkbox select_check" ></th>
<th style="width: 18%;">الاسم</th>
<th style="width: 5%;"></th>
<th style="width: 25%;">البريد الالكتروني</th>
<th style="width: 20%;">مدينة</th>
<th style="width: 20%;">اخر ظهور</th>
<th style="width: 50%;">زيارات الموقع</th>
</tr>
</thead>
<tbody>
<?php if (count($all_visitors) > 0): ?>
<?php foreach($all_visitors as $visitor) : ?>
<form method="POST">
<tr>
<td><input type="checkbox" name="select_checkbox[]" id="select_checkbox" class="checkbox selectall_checkbox" value="<?=$visitor['id']?>"></td>
<td><?= !empty($visitor['full_name']) ? $visitor['full_name'] : 'الاسم لم يعطى حتى الان'?></td>
<td><i class="fa fa-comments" aria-hidden="true"></i> </td>
<td><?= !empty($visitor['email']) ? $visitor['email'] : 'البريد الإلكتروني لم يعطى حتى الان'?></td>
<td><?= !empty($visitor['city']) ? $visitor['city'] : 'لم يتم إعطاء المدينة بعد'?></td>
<td><?= !empty($visitor['updated']) ? get_timeago(strtotime($visitor['updated'])) : '30 Seconds ago'?></td>
<td class="site-visits" ><?= !empty($visitor['total_visits']) ? $visitor['total_visits'] : '0'?></td>
</tr>
</form>
<?php endforeach; ?>
<?php else:?>
<tr><td colspan="6">No records found</td></tr>
<?php endif; ?>
</tbody>
</table>
Once you post data to your controller method,
access them like below
$ids=$this->input->post('select_checkbox');
If you do, print_r($ids), you will have values like below for example
Array ( [0] => 1 [1] => 2 )
Then, make create query and export to csv, codeigniter dbutil has easy way to transform your query to csv, below is snippet to do that,
public function export_csv()
{
/* Usually ids will be integers, so lets just filter only integer ids
from user input,
1st RULE : Never Trust User Inputs
2nd RULE : always validate User Inputs
*/
$ids = array_filter( $this->input->post('select_checkbox'), 'is_int');
if($ids)
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->select('Id', 'Name', 'Email', 'Phone', 'Created', 'Status')
->where_in('Id', $ids)
->get("your_table");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
/* output to browser */
force_download('Somereport.csv', $data);
}
}
if you prefer to download on click of somebutton, then your JQuery snippet would be,
$(function(){
/* Easy way is to set
action="http://example.com/your_controller/export_csv"
in your export form and then submit
*/
$('#your_export_button_outside_form').on("click",function()
{
/*
$('#your_export_form').attr('action','http://example.com/your_controller/export_csv');
*/
$('#your_export_form').submit();
});
})

Getting undefined variable error when passing a PHP variable as a link on an anchor tag on the view

Am working on a Laravel application whereby I fetch some data from an API (which is an executable link which opens a PDF document when clicked). Am fetching the data storing in a variable then pass to the view but when I add it inside the href attribute of anchor tag I get error of Undefined variable: quotePdf.
But when I get the data after dd and paste it in the anchor link tag it works perfectly
AJAX code rendering the view
$.ajax({
type: "POST",
url: "getquote",
data: JSON.stringify(allData),
contentType: "application/json",
dataType: "json",
cache: false,
success: function(data){
//The url that will render the view called quote.blade.php
window.location.href="showquote" ;
},
error: function(data) {
var errors = '';
for(datos in data.responseJSON){
errors += data.responseJSON[datos] + '\n';
}
alert(errors);
}
});
Controller that fetches the code and shows on the frontend
public function createQuote(Request $request)
{
$quote = $this->global_Curl_Meta(
$data, 'api/travel/create-quote')->data;
//dd($quote);
$quote_data = $quote;
$quoteholder_name = $form['FirstName'] . ' ' . $form['MiddleName'] . ' ' . $form['LastName'];
$quoteholder_email = $form['email'];
$travel_plan = $plan;
$quoteID = $quote_data->QuotationId;
$quoteRef = $quote_data->QuoteNumber;
$data = [
'sts_quote_number' => $quoteRef
];
//STS PDF Quote
$quotePdf = $this->global_Curl_Meta(
$data, 'api/v1/travel/sts-quote-doc')->data;
//dd($quotePdf);
//Get all teh variables and return to the view
$quote_data = view("B2C::travel.quote", compact('quote_data', 'quoteholder_name', 'quoteholder_email', 'travel_plan' ,'phone' , 'quotePdf' ));
return 'true';
}
Response on the browser after dd
data:application/pdf;base64,JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PAovQ3JlYXRvciAoQXBhY2hlIEZPUCBWZXJzaW9uIFNWTiB0YWdzL2ZvcC0xXzEpCi9Qcm9kdWNlciAoQXBhY2hlIEZPUCBWZXJzaW9uIFNWTiB0YWdzL2ZvcC0xXzEpCi9DcmVhdGlvbkRhdGUgKEQ6MjAxODEyMjcwODA0NTkrMDInMDAnKQo+PgplbmRvYmoKNSAwIG9iago8PAogIC9OIDMKICAvTGVuZ3RoIDExIDAgUgogIC9GaWx0ZXIgL0ZsYXRlRGVjb2RlCj4+CnN0cmVhbQp4nJ2Wd1RU1xaHz713eqHNMNIZeu9tAOldQHoVhWFmgKEMMMwAIjZEVCCiiIhgAwkKGDAaisSKKBaCggL2gAQBJQaj2FDJjKyV+PLy3svL7497v7XP3ueeXc5aFwCSdyorLQuWAiCNJ+AHe7nSI6Oi6dh+AAM8wAAzAJisrAz/EM9QIJKPhxs9S+QE/kWvhwEkft8yEu8F/j9JszL4AgCgQBFbsDlZLBEXijg1R5Ahts+KmBqfImYYJWa+6IAilhNz4iIbfvZZZGcxs9N4bBGLz5zBTmOLuUfEW7OFHBEjfiIuyuZyckR8W8SaqcI0rojfimPTOExRDiiS2C7gsJJEbCpiEj802E3ESwHAkRK/4PgvWMDJFYiTckvPWM3nJiYJ6LosPbqZrS2D7s3JSeUIBEaBTFYKk8+mu6WnZTB5qwFYzPmzZMS1pYuKbG1ma21tZG5s9kWh/uvi35S4t4v0MuhzzyBa3x+2v/JLrwOAMSeqzY4/bPF7AejYDIDcvT9smocAkBT1rf3GF/nQxPOSJBBk2JmY5OTkGHM5LGNxQX/X/3T4G/rie8bi7X4vD92dk8AUpgro4rqx0lPThXx6VgaTxaEb/XmI/3HgX5/DMJiTwOFzeKKIcNGUcXmJonbz2FwBN51H5/L+UxP
The view that is called quote.blade.php being rendered via AJAX, all the variables are being rendered well except quotePdf
#section('content')
#php
//var_dump($quote_data);
$quote_number = $quote_data->QuoteNumber;
$quote_details = $quote_data->Calculation_Quote->Calculation;
#endphp
<div class="container">
<main class="top Quote">
<h1 class="quote-title">Travel Insurance Quote
<!-- Go Back -->
<a href="#" onclick="goBack()">
<span class="back-us"><i class="fas fa-arrow-left"></i>Back</span>
</a>
<!--END-->
</h1>
<table class="table ref">
<thead class="thead-dark">
<tr>
<th colspan="6"> {{$quoteholder_name}} </th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="highlighted">Description</td>
<td colspan="2" class="highlighted">Pricing</td>
</tr>
<tr>
<td colspan="4"> Quote Reference </td>
<td colspan="2"> {{$quote_number}} </td>
</tr>
<tr>
<td colspan="4">{{$travel_plan}} Package </td>
<td colspan="2"> $ {{round($quote_details->TravelBasicPremium,2)}} </td>
</tr>
<tr>
<td colspan="4"><form>
</tr>
<tr>
<td colspan="4" class="highlighted">Total</td>
<td colspan="2" class="highlighted">$ {{round($quote_details->TravelTotalGrossPremium,2)}}</td>
</tr>
<tr>
<td colspan="2"><i class="fas fa-print quote"></i> Print Quote </td>
</tr>
</tbody>
</table>
<h1 class="notice">Important! Please review our policy, terms and conditions before you continue. <span class="noticeClick">CLICK HERE</span></h1>
<span class="glyphicon glyphicon-print"></span>
</main>
</div>
#endsection
try this one
$quote_data = view("travel.quote", ['quotePdf' => $quotePdf])->render();
otherwise used with method
$quote_data = view("travel.quote")->with('quotePdf',$quotePdf)->render();
Try like this,
Print Quote
I may be wrong but this is what I have observed.
public function createQuote(Request $request)
{
$quote = $this->global_Curl_Meta(
$data, 'api/travel/create-quote')->data;
//dd($quote);
$quote_data = $quote;
$quoteholder_name = $form['FirstName'] . ' ' . $form['MiddleName'] . ' ' . $form['LastName'];
$quoteholder_email = $form['email'];
$travel_plan = $plan;
$quoteID = $quote_data->QuotationId;
$quoteRef = $quote_data->QuoteNumber;
$data = [
'sts_quote_number' => $quoteRef
];
//STS PDF Quote
$quotePdf = $this->global_Curl_Meta(
$data, 'api/v1/travel/sts-quote-doc')->data;
//dd($quotePdf);
//Get all teh variables and return to the view
$quote_data = view("B2C::travel.quote", compact('quote_data', 'quoteholder_name', 'quoteholder_email', 'travel_plan' ,'phone' , 'quotePdf' ));
return 'true';
}
In your compact function, you are passing 'phone' as an entry which is not defined anywhere and hence it is ignoring each and every entry after that.
Try to remove 'phone' from compact function.
Instead of returning to base64 string ($quotePdf) to view. You can do something like this.
$decoded = base64_decode ($quotePdf);
$pdf = fopen ('quote.pdf','w');
fwrite ($pdf,$decoded);
fclose ($pdf);
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='quote.pdf'");
readfile("quote.pdf");
This code will decode base64 string and create a pdf file. and downloads the same. If you want return the view you can save the pdf in server and return the file path as a response.
Hope this helps!!

Export Table as Excel file in php

CSS is effecting in UI but not in Excel. Anyone can help me on this please.
Below code will export table into excel but not able to provide space before tags.
<?php
echo $excel_data = '<table border="1">
<thead>
<th align="left">S.No.</th>
<th align="left">Name</th>
<th align="left">DOJ</th>
</thead>
<tbody>
<tr>
<td align="left">1</td>
<td align="left">Sreekanth Kuriyala</td>
<td align="left">04-06-2015</td>
</tr>
<tr>
<td align="left">2</td>
<td style="padding-left:20px;">SK</td>
<td align="left">26-07-2015</td>
</tr>
</tbody>
</table>';
$excel_file = 'Reports.xls';
file_put_contents ($excel_file, $excel_data);
?>
</br>
</br>
<a href="<?php echo $excel_file; ?>" download>Export to Excel</a>
you have to create a CSV file just create new php file with a function that expects a result of a db select.
then just echo cols separated by ; and carrier return for next row.
this is a function i made:
<?php
function printcsv($result){
//result of database select
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=example.csv');
echo "\xEF\xBB\xBF";
$nl = "\n";
//this will be the carrier return var
if($rs = $result->fetch_array(MYSQLI_NUM)){
while($rs != ''){
echo $rs[0].";".$rs[1].";".$rs[2].";".$rs[3].";".$rs[4].";".$rs[5].";".$nl;
$rs = $result->fetch_array(MYSQLI_NUM);
}
}
}
?>
change my mysqli_fetch_array by your result desired fetch and try it =)
oh, and you cannot write tables on it, only echo data separated by semicolon. each data for each column, semicolon to put the next data in next column, and carrier return to write in next row.
cheers!

How to set table row to trigger jQuery hover event

When a user hovers the mouse over a table row, to trigger a preview event, only it doesn't react in any way. I think the problem is that the table rows are generated via PHP.
HTML & PHP
<table>
<thead>
<tr>
<th width="200">User</th>
<th width="900">Description</th>
</tr>
</thead>
<tbody>
<?php
require_once './Classes/MainController.php';
$mc = MainController::getInstance();
$threads = $mc->getAllThreads();
foreach ($threads as $thread) {
?>
<tr id='thread_video_preview'>
<td><?php print $thread->original_poster; ?></td>
<td><?php print $thread->description; ?></td>
<td id='see_thread_video_url' class="hide"><?php print $thread->url; ?></td>
</tr>
<?php } ?>
<script type="text/javascript" src="./Javascript/MainFunctions.js"> HoverPreview();
</script>
</tbody>
</table>
Jquery
function HoverPreview() {
$('tr#thread_video_preview').hover(function() {
var url = $(this).$('#see_thread_video_url').html();
$('#dynamicPreview').html('<iframe width="320" height="240" src="//www.youtube.com/embed/' + url + '?autoplay=1" frameborder="0""></iframe>')
});
}
There are several issues here. Firstly, id attributes should be unique. If you want to group elements, use a class. Secondly, the location of your script tag could cause issues. You should place it in the head, or just before </body>. Finally, when you set a src property of a script tag, you cannot place any code in it. You need a separate script tag for that. With all that in mind, try this:
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="./Javascript/MainFunctions.js"></script>
<script type="text/javacript">
$(function() {
$('tr.thread_video_preview').hover(function() {
var url = $(this).find('.see_thread_video_url').html();
$('#dynamicPreview').html('<iframe width="320" height="240" src="//www.youtube.com/embed/' + url + '?autoplay=1" frameborder="0""></iframe>')
});
});
</script>
</head>
In the body:
<?php
require_once './Classes/MainController.php';
$mc = MainController::getInstance();
$threads = $mc->getAllThreads();
foreach ($threads as $thread) { ?>
<tr class='thread_video_preview'>
<td><?php print $thread->original_poster; ?></td>
<td><?php print $thread->description; ?></td>
<td class='see_thread_video_url' class="hide"><?php print $thread->url; ?></td>
</tr>
<?php }
?>
Change this
<tr id='thread_video_preview'>
To :
<tr class='thread_video_preview'>
And in jquery event use
$(".thread_video_preview").
And I think it is good practice to use properties or event listener in td instead of tr

AJAX call does not post the data

I am developing a web site with Code Igniter 2.1.3. I am using an AJAX call to post data to my controller, but for some reason the data is not being sent.
I am using AJAX calls all over the application and they all work well, just not this one.
My view:
<div id="ajaxResult">
<div class="page-header"><h2>Review Comments</h2></div>
<div class="row-fluid">
<div class="span12">
<?php if(count($comments)): ?>
<table class="table">
<thead>
<tr>
<th>Author</th>
<th>Email</th>
<th>IP Address</th>
<th>Date</th>
<th>Comment</th>
<th>Approve</th>
</tr>
</thead>
<tbody>
<?php foreach($comments as $comment): ?>
<tr>
<td>
<?php echo $comment->comment_author; ?>
</td>
<td><?php echo $comment->comment_author_email; ?></td>
<td><?php echo $comment->comment_author_IP; ?></td>
<td>
<?php
$date = new DateTime($comment->comment_date);
$date = $date->format('d/m/Y');
echo $date;
?>
</td>
<td>
<?php echo $comment->comment_content; ?>
</td>
<td>
<?php
$approve = array(
'name' => 'comment_approved',
'class' => 'approve',
'value' => '1',
'data-commentid' => $comment->id
);
echo form_checkbox($approve);
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No comments were found for review.</p>
<?php endif; ?>
</div>
</div>
</div>
<script>
$(function()
{
$('.approve').on('click', function()
{
var id = $(this).data('commentid'); alert(id);
$.ajax({
url: "<?php echo site_url('blog/admin/review_comment'); ?>",
type:'POST',
data: { comment_id: id },
success: function(data) { $('#ajaxResult').html(data); } // End of success function of ajax form
}); // End of ajax call
});
});
</script>
My controller function:
public function review_comment()
{
$this->load->helper('form');
$this->load->model('blog_comment_m');
if(isset($_POST['comment_id']))
{
$id = $this->input->post('comment_id');
$data['comment_approved'] = 1;
$this->blog_comment_m->save($data, $id);
$this->data['comments'] = $this->blog_comment_m->get_by(array('comment_approved'=>0));
$this->load->view('admin/review_comments', $this->data);
}
else
{
$this->data['comments'] = $this->blog_comment_m->get_by(array('comment_approved'=>0));
$this->data['subview'] = 'admin/review_comments';
$this->load->view('admin/_layout_main', $this->data);
}
}
I tried to alert the comment_id and it does give me a value of 1. In the controller I do var_dump($_POST), always empty.
I also tried if(isset($_POST['comment_id'])). In the controller it never goes into the if(isset($_POST['comment_id']) statement.
Why is that?
Found it.
It was the fact that I started using csrf on form submits, a new thing for me, and I didn't add this url to the config file.
Adding this:
$config['csrf_exclude_uris'] = array('blog/admin/review_comment');
Solved the problem......
Thank you very very much for all the help.

Categories