How to export dynamic html table to doc file using php? - javascript

I'm new using PHP and I need a bit of help here.
I'd like to send a HTML table to another PHP file, and then, be to able to use this information (specifically I want to download this like DOC file).
I've seen a lot of information how to do it. But I haven't seen how to do without <tbody></tbody>. I have a dynamic table, so, the data is loading from an array. By the way, I'm using DataTable-jQuery to do it.
I have the following HTML code:
<form action="sectoresTable.php" method="post">
<table id="sectoresTable">
<thead>
<tr>
<th><b>#</b></th>
<th><b>Numero</b></th>
<th><b>Nombre</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="submit" style="margin-top: 20px;">Exportar</button>
</form>
and sectoresTable.PHP:
<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=TablaSectores.doc");
echo '';
?>
By the way, to load the data into the table, I'm using the following script:
<script>
$('#sectoresTable').DataTable({
data: arraySectores
});
</script>
In general all this is working good, I download a doc file but without information (and That is right because my echo is printing nothing.).
I understand that I need to use a foreach in my HTML code? But really, I'm not sure.

try to use an api,to export dynamic html table to doc file in php
http://www.phpclasses.org/package/2763-PHP-Convert-HTML-into-Microsoft-Word-documents.html

Related

Filtering using ajax

I'm a FileMaker programmer trying to port a database across to the web using PHP their API. I've got my php page working, retrieving and displaying the correct data from my search, however I would like to filter the results on my page every time my user picks a checkbox (Apple, Microsoft etc) without hitting the submit button. I know I need to use ajax to perform this, however can I inject the ajax into this page below or am I now going to have to break down the page into various smaller files, php and js files?
Most of the samples I have found are json based, which do filtering client side. FileMaker returns an odd type array with PHP which requires further processing to get into json format. I'm ideally looking for a way to just post back the form everytime my user click on a checkbox, which I think maybe simpler if possible?
<?php require_once('../db.php');
if(isset($_REQUEST['search'][0]))
{
$find = $fm->newCompoundFindCommand('Data');
$request1 = $fm->newFindRequest('Data');
if(isset($_REQUEST['search'][1])){ $request2 = $fm->newFindRequest('Data'); }
if(isset($_REQUEST['search'][2])){ $request3 = $fm->newFindRequest('Data'); }
$request1->addFindCriterion('Company',$_REQUEST['search'][0]);
if(isset($_REQUEST['search'][1])){ $request2->addFindCriterion('Company',$_REQUEST['search'][1]); }
if(isset($_REQUEST['search'][2])){ $request3->addFindCriterion('Company',$_REQUEST['search'][2]); }
$find->add(1,$request1);
if(isset($_REQUEST['search'][1])){ $find->add(2,$request2); }
if(isset($_REQUEST['search'][2])){ $find->add(3,$request3); }
$result = $find->execute();
} else {
$request = $fm->newFindCommand('Data');
$request->addFindCriterion('Company','*');
$result = $request->execute();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<div id="filters">
<form action="data_table.php" method="post">
<input class="category" id="check1" name="search[]" type="checkbox" value="Apple">
<label for="check1">Apple</label>
<input class="category" id="check2" name="search[]" type="checkbox" value="Google">
<label for="check2">Google</label>
<input class="category" id="check3" name="search[]" type="checkbox" value="Microsoft">
<label for="check3">Microsoft</label> <input type="submit" value="Submit">
</form>
</div>
<table border="0" class="table table-striped" width="100%">
<thead>
<tr>
<th>Company</th>
</tr>
</thead><?php if(!FileMaker::isError($result)) {?>
<tbody class="searchable">
<?php foreach($result->getRecords() as $row){ ?>
<tr>
<td><?php echo $row->getField('Company'); ?></td>
</tr><?php } ?>
</tbody><?php } ?>
</table><!-- end row -->
</body>
</html>
Let me try and break down you code part.
$request->addFindCriterion('Company','*');
$result = $request->execute();
At this point you have the results after applying the query. Just encode it in json like
echo json_encode($result);
this is your api endpoints. You will be making all ajax queries over here. Move all html content to a separate file.
Now this part of code
<table border="0" class="table table-striped" width="100%">
<thead>
<tr>
<th>Company</th>
</tr>
</thead><?php if(!FileMaker::isError($result)) {?>
<tbody class="searchable">
<?php foreach($result->getRecords() as $row){ ?>
<tr>
<td><?php echo $row->getField('Company'); ?></td>
</tr><?php } ?>
</tbody><?php } ?>
</table><!-- end row -->
becomes obsolete as you might have guessed for obvious reasons. There is no $result in this file. It is just a static html. You need to make ajax request in this file to the api point we just used above. You will get the response in json. Populate it into a table. Similarly if the users has other search parameters, make ajax request with proper search and repopulate the table in javascript.
Which part is simpler ?
That purely depends on the kind of application you are building. If it is somewhat along the lines of Single Page app i would suggest javascript filtering else go for filter in api.
Remember javascript does not have proper sql database and they are implementations of localstorage so the execution might be long, but that is a tradeoff people make for persistant apps.

How To Rename Files that Being Downloading using Javascript and PHP Header?

just like my title how can I do that thing?
I tried to code like below (in file view_report.php)
<?php
header('Content-Disposition: inline;filename=report_loader.txt');
?>
<div id="reportTable">
<table>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach($reports->result() as $rows): ?>
<tr>
<th><?php $rows->no; ?></th>
<th><?php $rows->name; ?></th>
</tr>
</tbody>
</table>
</div>
<div class="row">
<input type="button" class="btn btn-success btn-sm" value="Generate Excel" id="exportExcel" />
</div>
<script>
$("#exportExcel").click(function (e) {
window.open('data:application/vnd.ms-excel,' + $('#reportTable').html());
e.preventDefault();
});
</script>
EDIT
That is my entire code. I already tried it. I referred some questions in this Site, but I don't fine clean solution for me. I actually have tried to use Content-Disposition: inline and Content-Disposition: attachment. But still not working. The browser (I tried on Chrome and Firefox), it returns random file name, not the file name I want. Can anyone help me to find this solution?
I think there is no "inline" for Content-Disposition.
Can you try:
header('Content-Disposition: attachment;filename=report_loader.txt');
Update:
Sry, there IS inline for Content-Disposition. But you should use that if you want the browser to display the content, not download it. Therefore it will probably ignore the filename attribute.
Source:
http://www.ietf.org/rfc/rfc1806.txt
Update 2:
Try this:
var blob = new Blob([$('#reportTable').html()], {type: "text/html;charset=utf-8"});
saveAs(blob, "table.html");
This should save the HTML from #reportTable as table.html
Note: If you want to create an Excel file, you will need more than just the html source.
Example:
Download Your Downloading Thingy
Please, check this documentation:
https://developer.mozilla.org/en/docs/Web/HTML/Element/a
It states:
download
This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file. If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link (the user can change the name before actually saving the file of course). There are no restrictions on allowed values (though / and \ will be converted to underscores, preventing specific path hints), but you should consider that most file systems have limitations with regard to what punctuation is supported in file names, and browsers are likely to adjust file names accordingly.
You can try this:
$file_name='abc.txt';
header("Content-Disposition: attachment; filename=" .$file_name);

How to read the $_FILES['name']['tmp_name'] using jQuery

I'm making an application to import excel to database using excel_reader2.php. I created a form for uploading excel file and when the file that I want to upload selected, I want to read data boundsheet of the excel file. which become problems when I using js, I could not parsing the $ _FILES in php code.
<script type="text/javascript">
function sheetChange()
{
var html;
$("#sheetName td").remove();
var fileInputContent = $('#form').serializeArray();
$.post(basedomain+"mycontroller/readSheet",fileInputContent,function(result)
{
if(result)
{
$("#sheetName").show();
var data = JSON.parse(result);
html += '<td>Sheet Name</td><td colspan=\'3\'><select name=\'SHEET\' required>';
for(var i in data)
{
html += '<option value=\''+data[i]+'\'>'+data[i]+'</option>';
}
html +='</select></td>';
$("#sheetName").append(html);
}
});
}
</script>
<form id = 'form' method="post" action="upload.php" enctype="multipart/form-data">
<table cellspacing="0" cellpadding="0">
<tr>
<td>Input Xls File</td>
<td colspan="3"><input type="file" name="file" id="file" onchange="sheetChange()"/></td>
</tr>
<tr id="sheetName"></tr>
</table>
</form>
php code:
public function readSheet()
{
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader($_FILES['file']['tmp_name']); //$_FILES is null
foreach ($data->boundsheets as $k=>$sheet)
{
$row[] = $sheet['name'];
}
echo json_encode($row);
exit;
}
anyone can help me?Thanks in advance.
the reason is that uploading files using HTML is not as simple as you might think. Here are two nice examples how a normal POST looks like (in the HTTP Protocol) versus how a multipart/form-data request looks like:
http://www.htmlcodetutorial.com/forms/form_enctype.html
The thing to take away from here is, that form submits and form submits with file upload are technically two very different things.
$.post can only do the normal form submit for you, file uploads are not supported by jQuery.
There are two ways you can get around this:
just do a plain form submit (the simpler approach)
you'll have to programmatically add the file to the request. If you go for this option, there's a plugin you might use (never tried it though): https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data
Cheers,
Matthias

Creating unique URLs/Pages from MySQL DB on HTML form submit

The forums have been a huge help on this project so far. I'm looking for some guidance on the next step of my project here.
What I have is a form that feeds user submitted information into a MySQL database. This database then feeds this information to a main page displaying all of the information in the DB. What I am looking to do is add something to my form that creates a new unique URL/page when the form is submitted. I have already designed the HTML/CSS template for this page and it is designed to display only one set of information as opposed to the entire DB worth.
I am looking for some guidance as to how I can create the pages and unique URLs on the form submit. What is the best way to get this fresh information feeding from the DB immediately?
I need to somehow automatically recreate the HTML and CSS files as well on the server, this I am unfamiliar with.
EDIT: After #Jacky Cheng pointed out that this was possible without creating new versions of the HTML/CSS files I would be inclined to go about having a single HTML file on the server that is dynamic.
Thanks for any help as you guys have been great so far.
Including code for the form which I am submitting to the DB from, and the page which I will be pulling info from.
This is the form:
<?php
include_once 'post_func.inc.php';
connect();
?>
<!DOCTYPE html>
<html>
<head>
<title>Event Register</title>
</head>
<body>
<div style="text-align: center">
<h2>Event Register</h2>
<form id="eventregister"action="eventtestconnect.php" method="post">
<table style="border: 0; margin-left: auto; margin-right: auto; text-align: left">
<tr>
<td>Event Name:</td>
<td><input name="name" type="text"></td>
</tr>
<tr>
<td>Event Type:</td>
<td>
<select name="eventtype">
<?php query_eventtype() ?>
</select>
</td>
</tr>
<tr>
<tr>
<td>Venue:</td>
<td>
<select name="venue">
<?php query_venue() ?>
</select>
</td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</div>
</body>
<?php close() ?>
</html>
This is the page I want filling with information from the DB after the form is submitted and the url is generated.
<?php
include_once 'event_func.inc.php';
connect();
?>
<html>
<head>
<title>
<?php query_eventname() ?>
</title>
<link href="eventstest.css" rel="stylesheet" type="text/css"/>
</head>
<body id="body">
<div id="maincontainer">
<div id="header">
</div>
<div id="content">
<div id="eventname">
<?php query_eventname() ?>
</div>
<div id="eventvenue">
<?php query_eventvenue() ?>
</div>
<div id="eventicon">
<?php query_eventtype() ?>
</div>
</div>
</div>
</body>
<?php close() ?>
</html>
What changes need to be made to the form in order for the url to be generated on submit and the event page to be able to jump between urls/sets of data dynamically, per-say?
Sorry for the beginner questions but this site really seems to be the best resource for these sorts of things and I haven't found anything this specific on here!
Thanks again for the help!
I am still half guessing what you want, so bear with me here.
from the description of your question, you seems to have a system that would generate an actual html file per form submit? That doesn't look good to me.
maybe try something like this :
redesign a web page that would take http GET request parameter as input (mydomain.com/display.php?id={input1}) and display only 1 set of info.
from the comments I see you have a unique id per form submit, I'd suggest avoid using it directly in the request as it'll be extremly easy to get someone else's info. Instead try somthing like MD5 encoding for that id and then sending that out to user.
so the overall system would be:
1) you'll only ever have 1 html file in your server, which will dynamically change it's content according to input, which save you a lot of space.
2) you'll have a unique & slightly more secure URL per form submit
edit:
here are some fake code to show the general idea.
form response:
$uniqueId=mysql_query("SELECT unique_id FROM my_db");
echo "http://yourdomain.com/display.php?urlid=".$uniqueId;
display.php
<?php
$uniqueId=$_GET['urlid'];
mysql_query("SELECT info_you_need FROM your_tables WHERE unique_id = $uniqueId");
?>
<html><body>your display page html here</body></html>
I guess...
You want to create product catalog page like this:
www.abc.com/Electronics/Product-Motorola-moto-g-at-Rs6999-only.html
and this will display all the product information from the database.
If the above is your case then you can use url rewrite in your project.
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^Product-/?$ Product-Motorola-moto-g-at-Rs6999-only.html [NC,L] # Handle requests for "Product-"
The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:
RewriteRule - Tells Apache that this like refers to a single RewriteRule.
^/Product/?$ - The "pattern". The server will check the URL of every request to the site to see if this pattern matches. If it does, then Apache will swap the URL of the request for the "substitution" section that follows.
Product-Motorola-moto-g-at-Rs6999-only.html - The "substitution". If the pattern above matches the request, Apache uses this URL instead of the requested URL.
[NC,L] - "Flags", that tell Apache how to apply the rule. In this case, we're using two flags. "NC", tells Apache that this rule should be case-insensitive, and "L" tells Apache not to process any more rules if this one is used.
Handle requests for "Product" - Comment explaining what the rule does (optional but recommended)
Hope this will work for you.
Feel free to ask any help.
Happy programming :)
Bear with me too. Your description is pretty bad. So if I am correct, you want form=>mysql=>confirmation
So, form should be action="process.php" method="post"
Create a process.php file where you do your validation, escaping, serializing, etc. Insert into the MySQL table. If returns true redirect (header(location:yourdomain.com)) and then on the redirected page, select the information from the Database.

javascript generating php doens't works

Hello I have an option list in html that is created dynamically by php. I want to take the value of the option list withought subbmiting everything and then call another php function to fill another option list. To be more specific I want the user to first pick a University from a database and then to pick a department of that Universe. I 've created dynamicaly the option list for the Uni's by fetching all Uni's from the database and then find the value by javascript. So in the javascript function I want to write php code in order to fetch all the departments from the university. Eveything works fine until I try to call the php function from the javascript.
signup.php
<form>
<table>
.
.
.
<tr>
<td> Ίδρυμα:</td>
<td><select id="selection" name="selection" onchange="selectDep()" >
<?php include './selectUni.php'; ?>
</select> </td>
<td><span id="orgError" style="display: none;"></span> <td>
</tr>
<tr>
<td> Τμήμα:</td>
<td id="dep" name="dep" ></td>
<td><span id="depError" style="display: none;"></span><td>
</tr>
.
.
</table>
</form>
generateDep.js
function selectDep(){
if(document.getElementById('selection').value === "---")
return;
var value=document.getElementById('selection').value;
alert(value);
document.getElementById('dep').innerHTML=" <?php include './selectDep.php'; selectDep("+value+"); ?> ";
return true;
}
the value at the alert is correct
selectDep.php
<?php
//just trying to make this work for now
function selectDep($value){
echo $value;
}
?>
I cannot understand what I am doing wrong. Everything look fine to me. Can you help me?
First You have to understand that the javascript code executes in web browser but the php code executes in web server.
You can use AJAX to fix your problem.
PHP is a server-side scripting language. It is executed on the server, which means the page has to submit values to the server as a trigger. Javascript and HTML are client-side, which means it's all done in the browser without communicating with the server.
To see this in action, right-click on a PHP page in the browser and select to view source. All you will see is the HTML, you will not be able to view any of the PHP code that generates the page. When PHP executes on the server, the result is client-side code (javascript, HTML and maybe CSS) which is sent to the browser.
The browser wouldn't know what to do with PHP code. If you set the inner HTML of an element to some PHP code in client-side script, it won't get executed and all you will achieve is having the browser render the PHP script exactly as you entered it.
In short, the javascript has to submit the selected value back to the server, before the server-side PHP can work out which departments to send back to the browser.

Categories