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

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

Related

How do I save form data to a text file?

I know this question has been asked before, but I'm trying to diagnose why this isn't working. I want to write form data into a .txt file using a post request. I don't know much PHP at all, as this is a quick program I'm patching together. Here's the code:
Javascript:
function submitdata() {
document.querySelector("#val").innerHTML = input.value + ": " + input1.value;
document.querySelector("#submitform").submit(); }
HTML:
<form style="display: none;" method="POST" name="myform" id="submitform">
<input id="val" name="val">
</form>
PHP:
<?php
if(isset($_POST['val']))
{
$data=$_POST['val'];
$fp = fopen('data.txt', 'a+');
fwrite($fp, $data);
fclose($fp);
}
?>
How does your browser know where to send the form data?
You need to specify the php file name in form action attribute.
Edit- added relevant point from comment below.
I have pointed out the obvious error based on what you have provided, but it might not be the only one. Other error is you are using innerHTML on an input element. So this may not set the value for #val (some browsers may set the value, some may not).

How do I put javascript value into a php variable without changing the page?

I've got this research.php file that should show the content of a database table, taking the informations for the query from a javascript form.
I made in javascript the form and disabled the enter key, so that only by hitting the button you can submit the value. The value of the components in the form should be used to make the query. Can I pass the value to a php variable in the same file?
<!DOCTYPE html>
<html>
<head>
<!--
Implemented by Argese Alessandro and Rosso Kevin
The slider is taken from "https://dhtmlx.com/docs/products/dhtmlxSlider/samples/index.html"
Download slider: "https://dhtmlx.com/docs/products/dhtmlxSlider/"
-->
<title>Ricerca diplomati</title>
(...) <!--slider things-->
<style>
(...)
</style>
<script>
var mySlider;
function doOnLoad(){ //slider load
(...)
};
function doOnUnload(){ //slider unload
(...)
};
window.addEventListener('keydown', function (event) {
// if the keyCode is 16 ( shift key was pressed )
if (event.keyCode == 13) {
// prevent default behaviour
event.preventDefault();
return false;
}
});
function interact(form){
(...) //here the value is put in js variables, for a test
});
</script>
</head>
<body onload="doOnLoad();" onunload="doOnUnload();">
<form id="filters" name="filters" action="#" enctype="text/plain">
<table cellspacing="0" cellpadding="0" border="0" class="filters_table">
<tr>
<td>Specializzazione:</td>
<td>
<select name="specialization" class="table">
<option selected value="0">Tutte le specializzazioni</option>
<option>Chimica</option>
<option>Elettrotecnica</option>
<option>Informatica</option>
<option>Meccanica</option>
</select>
</td>
<td></td>
<td></td>
<td>Valutazione finale:</td>
<td><div id="sliderObj"></div></td>
<td><span id="sliderLink"></span><span class="minussign">-</span><span id="sliderLink2"></span></td>
<td></td>
<td></td>
<td>Città:</td>
<td><input type="text" name="city" size="35" maxlength="40" value=""></td>
<td></td>
<td><input type="button" onclick="interact(filters)" value="search" style="background: url(res/magnifying-glass-16x.png); background-repeat: no-repeat; background-position:center; background-color: #0c84e4;width:24px; height:24px;"></td>
</tr>
</table>
</form>
<?php
function viewTable(){
echo "Here the table will be shown";
}
?>
</body>
</html>
In this code the button click just call the interact function, that show an alert window with the value of the variables.
I tried to use ajax but, as far as I understood, it would open a new file.
I've also seen a solved answer in which someone suggested to use the cookies, but that solution really disgusted me.
The most helpful thing I found is here:
How do i store select value into a php variable,
but the POST method refresh the page and the slider crushes.
If you want to pass a variable from JS to PHP you are going to want to use AJAX, it allows you to send and receive info from server running the PHP script.
Your Javascript:
var infobeingsent = "test";
$.ajax({
type: "POST",
url: 'YOURPHPFILE.php',
data: { testVAR : infobeingsent },
success: function(data)
{
alert("data has been sent");
var recievedvar = data;
}
});
Your php file:
if(isset($_POST['testVAR']))
{
$recievedvar = $_POST['testVAR'];
echo "Hey, ive recieved your request";
}
Using AJAX means that your browser never has to come into direct contact with the php file and there's no interruption from the end-users perspective
I think you are a bit confused about the whole work flow between php (server side) and js (client side). OR may be I got your question wrong. But here is a hint on how you can approach this.
You have a server side running php - Great.
You have an html page with js - Awesome.
In the html page, you have a form that you want to run a query based on the user submission:
AJAX is the way. You can do it with pure javascript or a plugin like jquery. On the php side, you can even keep a small, seperate script just to handle this request, run the query and generate the result. Use "onSubmit" for the form to invoke ajax.

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

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

Submitting embedded pdf in html form

I've searched in vain for days, but haven't found a solution for my problem yet.
Ideally, I would like to embed a fillable pdf form into an intranet html form for submission to the server for processing (ability to parse the field/values would be gravy, but not required). The files are all in the same domain so no cross-domain issues. I know I could add submission functionality to the pdf form itself, but 1) scripting is beyond the ability of the pdf document administrator and I don't want to take that on, 2) there are hundreds of pdf documents, 3) I need additional scripted fields/values submitted with the form, 4) I want the pdf document to be contained within the login session. So far, the server log shows all the field/values, except the PDFInput parameter which is passed, but the value is empty.
Here's what I have so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(uploadForm).on("submit", function(event) {
var iframe = document.getElementById('PDFObj');
var iframeDocument = [iframe.contentDocument || iframe.contentWindow.document];
var pluginData = iframeDocument;
$(this).append('<input type="file" name="PDFInput" id="PDFInput" value="' + pluginData + '" style="visibility:hidden"/>');
return true;
});
});
</script>
and
<form enctype="multipart/form-data" method="post" name='uploadForm' id='uploadForm'>
<input type='hidden' name='rm' id='rm' value='uploadFile'>
<table align='center'>
<tr>
<td align='left'>
<strong>Notes:</strong>
<br>
<textarea cols='80' rows='2' name='notes' id='notes'></textarea>
<br>
<br>
</td>
</tr>
<tr>
<td colspan=2 align='center'>
<input type='submit'>
</td>
</tr>
<tr>
<td colspan=2>
<br>
<input type='hidden' name='formid' id='formid' value='6F45B3AF-91F3-108C-D3D9-701F541B49DC'>
<iframe type='application/pdf' src="url.pl?formid=6F45B3AF-91F3-108C-D3D9-701F541B49DC.pdf" height='800' width='1000' name='PDFObj' id='PDFObj'>
</td>
</tr>
</table>
</form>
I've tried embedding it using iframe and object along with setting input type="object", but I can't get any combination to work.
Is this even possible? Is there a better approach?
As far as I know, you're not going to be able to capture the PDF data directly from HTML like that. Your best bet is going to be to add submit functionality to the PDFs, then process the resulting FDF data with a server-side script.
You will need either add Submit a Form buttons to your PDFs, or modify the existing buttons. Make sure the form action in the PDF has #FDF after the URI (eg https://example.com/process.php#FDF).
Parsing the data server side is simple. I'm not sure what server side language you are using, but here is a PHP snippet
<?php // process.php, report the data we received
echo '<h2>GET Data</h2>';
foreach( $_GET as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
echo '<h2>POST Data</h2>';
foreach( $_POST as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
Note that a PDF only interacts with a web server properly when viewed inside of a web browser.
I do not know of a reliable way to programmatically add submit buttons to PDFs, nor do I know of a reliable conversion method. You're between a rock and a hard place here IMHO.
More info:
http://www.w3.org/TR/WCAG20-TECHS/PDF15.html
http://etutorials.org/Linux+systems/pdf+hacks/Chapter+6.+Dynamic+PDF/Hack+74+Collect+Data+with+Online+PDF+Forms/

How to parse CSV file and store it's data into database?

I trying to store CSV data to database using onclick function. Unfortunately, I am using php code inside javascript function which is not efficient enough. Therefore, I hope that I can get any suggest or solution to improve efficiency of my project by using javascript instead of php to store CSV data into database.
This is javascript with php code :
<script>
function storeQueEmail(){
<?php
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_first'] = $data[0];
$record['contact_last'] = $data[1];
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
?>
}
</script>
This is HTML code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your upload type: <br />
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit" onclick="storeQueEmail()"/>
</form>
</body>
</html>
what are you trying to do there? I think you are speaking about a PHP in
HTML document. So your PHP code inside your function is interpreted on server. As your PHP code has no output your Javascript function is simply empty. Thus as you have registered your Javascript function as onclick handler just nothing would happen.
Remember that standard Javascript code is interpreted on Client (that means in browser) though you PHP code is interpreted on server. As mentioned in the comments above it is possible to use an AJAX or POST/GET - Request to send data to your server and then write it to your DB or file etc.
Another way to do this directly with Javascript is Node.js - serverside Javascript that is able to write to your Database like PHP can do.
The easiest way for you to do it with your HTML code you presented above is to fill in your
action - attribute
in your
form tag
For example:
<form action="proccessData.php" ...>
...
</form>
Don't forget to remove your onclick - attribute inside form's submit input field.
If you know press your submit button your entire form and its content will be send to http://www.xyz.de/proccessData.php. Inside that file you can work with your form data: In your case two text fields and one file upload field. As you may know you could get to the content of text input field send via post via:
$_POST['<name of field>']
To get your uploaded file and proccess it you could use PHP's global
$_FILE[] - Array
Just refer to PHP's manual on php.net or some other online documentation. There's pretty much to find on the web.
I just give you a helpful link to php.net on how to handle file uploads in a correct and therefor secure manner: http://us2.php.net/manual/en/features.file-upload.php
Once you have read your uploaded file via PHP's global $_FILE[] - array just proccess that file via fgetcsv in your proccessData.php and write it line for line to your database.
Hope that helps! It is really not that hard :)

Categories