PHP not parsing Javascript created HTML forms - javascript

I have HTML forms being created by Javascript. I also have regular forms not created by Javascript. When I submit the regular HTML form, the PHP script parses it just fine, but when I submit the Javascript created forms, it's not parsed. I can't for the life of me figure out why one parses, and the other one doesn't.
Javascript:
function addWeapon(){
var weapsForm = document.createElement("form");
weapsForm.setAttribute('name',"savefile");
weapsForm.setAttribute('method',"post");
weapsForm.setAttribute('action',"");
var weapsName = document.createElement("input");
weapsName.setAttribute('type',"text");
weapsName.setAttribute('name',"textdata[]");
var weapsNameQt = document.createElement("input");
weapsNameQt.setAttribute('type',"number");
weapsNameQt.setAttribute('name',"textdata[]");
weapsNameQt.setAttribute('value',"0");
var weapsNameSubmit = document.createElement("input");
weapsNameSubmit.setAttribute('type',"submit");
weapsNameSubmit.setAttribute('name',"submitsave");
weapsNameSubmit.setAttribute('value',"Done!");
weapsForm.appendChild(weapsName);
weapsForm.appendChild(weapsNameQt);
weapsForm.appendChild(weapsNameSubmit);
document.getElementsByTagName('body')[0].appendChild(weapsForm);
}
And here's the PHP code which parses the HTML form no problem. I'd also like to add, the Javascript created HTML is exactly the same as the regular HTML.
PHP:
<?php
if (isset($_POST)){
if ($_POST['submitsave'] == "Done!" && !empty($_POST['filename'])) {
foreach($_POST["textdata"] as $text){
if(!file_exists($_POST['filename'] . ".txt")){
$file = tmpfile();
}
$file = fopen($_POST['filename'] . ".txt","a+");
while(!feof($file)){
$old = $old . fgets($file);
}
file_put_contents($_POST['filename'] . ".txt", trim($text).PHP_EOL, FILE_APPEND);
}
fclose($file);
}
}
?>
Thanks for any help guys!
EDIT: I forgot to mention the "filename" field is in the HTML document, and is not created by Javascript.
EDIT: Also, the file is created on the server, but the forms are not being parsed.
EDIT: After messing with the code for a couple of hours, I realized it was in fact not parsing the "filename" field on the HTML document, but was parsing the Javascript form. Thank you guys for the help!

The form you are making with the Javascript is missing the filename field.. You either need to add the filename field in the Javascript for like below:
function addWeapon(){
var weapsForm = document.createElement("form");
weapsForm.setAttribute('name',"savefile");
weapsForm.setAttribute('method',"post");
weapsForm.setAttribute('action',"");
var weapsName = document.createElement("input");
weapsName.setAttribute('type',"text");
weapsName.setAttribute('name',"textdata[]");
var weapsNameQt = document.createElement("input");
weapsNameQt.setAttribute('type',"number");
weapsNameQt.setAttribute('name',"textdata[]");
weapsNameQt.setAttribute('value',"0");
var weapsfilename = document.createElement("input");
weapsfilename.setAttribute('type',"text");
weapsfilename.setAttribute('name',"filename");
weapsfilename.setAttribute('value',"SomeFile.txt");
var weapsNameSubmit = document.createElement("input");
weapsNameSubmit.setAttribute('type',"submit");
weapsNameSubmit.setAttribute('name',"submitsave");
weapsNameSubmit.setAttribute('value',"Done!");
weapsForm.appendChild(weapsName);
weapsForm.appendChild(weapsNameQt);
weapsForm.appendChild(weapsNameSubmit);
document.getElementsByTagName('body')[0].appendChild(weapsForm);
}
Or you need to change your conditional in php not to be based on the filename like so:
<?php
if (isset($_POST)){
if ($_POST['submitsave'] == "Done!") {
// New code parsing the other fields since you are no longer grabbing a file
}
}
?>

Looking at your code it seems that you need to add following code in your javascript.
function addWeapon(){
var weapsForm = document.createElement("form");
weapsForm.setAttribute('name',"savefile");
weapsForm.setAttribute('method',"post");
weapsForm.setAttribute('action',"");
var weapsName = document.createElement("input");
weapsName.setAttribute('type',"text");
weapsName.setAttribute('name',"textdata[]");
var weapsNameQt = document.createElement("input");
weapsNameQt.setAttribute('type',"number");
weapsNameQt.setAttribute('name',"textdata[]");
weapsNameQt.setAttribute('value',"0");
var weapsFile = document.createElement("input");
weapsFile.setAttribute('type',"file");
weapsFile.setAttribute('name',"filename");
weapsFile.setAttribute('value',"0");
var weapsNameSubmit = document.createElement("input");
weapsNameSubmit.setAttribute('type',"submit");
weapsNameSubmit.setAttribute('name',"submitsave");
weapsNameSubmit.setAttribute('value',"Done!");
weapsForm.appendChild(weapsName);
weapsForm.appendChild(weapsNameQt);
weapsForm.appendChild(weapsFile);
weapsForm.appendChild(weapsNameSubmit);
document.getElementsByTagName('body')[0].appendChild(weapsForm);
}
And in php you need to print $_FILES instead of $_POST to get filename.

I gues your $_POST['filename'] is empty.
empty() function in php check is variable has some value. So if you do not choose your file it will return true ( empty ). Try to use isset() if you need to check is your input was sent.

Related

Angular JS app: save excel file and show it later

In my application (developed with AngularJS framework) I must create and download an excel file in client side (Javascript language). To do this, I have this code
var form = document.createElement('form');
form.action = 'download';
form.method = 'POST';
form.style.display = 'none';
var inputsrtoken = document.createElement('input');
inputsrtoken.style.setAttribute("width", "0");
inputsrtoken.style.setAttribute("diplay", "none");
inputsrtoken.style.setAttribute("visibility", "hidden");
inputsrtoken.type = 'text';
inputsrtoken.name = 'srtoken';
inputsrtoken.value = token;
var inputData = document.createElement('input');
inputData.style.setAttribute("width", "0");
inputData.style.setAttribute("diplay", "none");
inputData.style.setAttribute("visibility", "hidden");
inputData.type = 'text';
inputData.name = 'inputRicalcolo';
inputData.value = JSON.stringify(excelData);
var submit = document.createElement('input');
submit.type = 'submit';
submit.id = 'submitProject';
form.appendChild(inputsrtoken);
form.appendChild(inputData);
form.appendChild(submit);
document.body.appendChild(form);
$('#submitProject').click();
document.body.removeChild(form);
Where in variable excelData are included some usefull information for the generation of excel file.
Server side, I have this code (in the download servlet)
if (Base64.isArrayByteBase64(excelin.getBytes("UTF-8"))) {
excelin = new String(Base64.decodeBase64(excelin.getBytes("UTF-8")), "UTF-8");
}
bpdf = createExcelRicalcolo(excelin);
String chiave = request.getParameter("chiave");
DateFormat formatter = new SimpleDateFormat("ddMMyyyy-HHmm");
String format = formatter.format(new Date());
String filename = "RICALCOLO_ONLINE_"+chiave +"_"+ format + ".xls";
byte[] b = bpdf;
if (b != null) {
int length = b.length;
ServletOutputStream op = resp.getOutputStream();
resp.setContentType("application/ms-excel");
resp.setContentLength(length);
resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
resp.setHeader("Expires", "0");
resp.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
resp.setHeader("Pragma", "public");
op.write(b);
op.flush();
op.close();
}
It works great!
But now, this is my question: is it possible to generate the file, without downloading it, but only to save it (maybe with a service in javascript) for a subsequent download request?
In fact, my goal is the following: I would like to generate an excel file (and not show to the user), save it on a DB2 column as a CLOB and only then (by pressing for example another button on the app) give the user the possibility to download it.
Do you believe it is possible to do such a thing without upsetting the logic of the code?
Saving the file as a CLOB will be the following problem to be framed.
Grace to anyone who will try to help me.

Attempting to Post String to PHP dynamically

Using JavaScript only I want to POST a string to php file and redirect to it at the same time, however, my php file is not picking up the information.
JavaScript:
var data = "&id=" + obj.id;
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
form.value = data;
document.body.appendChild(form);
form.submit();
};
redirect("summary.php","POST");
And the PHP code is simply (NO ERROR HERE, JUST FOR CONVENIENCE):
$id = $_POST['id'];
EDIT:
The problem is that the PHP file is not picking up the name "id". There is no problem in the php file or how I structure my data.
You made a small typo. ALthough it is a huge problem. In PHP you create variables using the $ sign.
var data = "id=" + obj.id;//you don't necessarilly need the & as you are only passing one item(value)
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
//form.value = data;//this won't work. form does not have value attribute:
//create input element
var i = document.createElement("input");
i.type = "text";//set type.
i.name = "id";//set name of the input
i.id = "id";
i.value = obj.id;//set value of input
form.appendChild(i);//add this input to the form
document.body.appendChild(form);//add the form to the body
form.submit();//dynamically submit
};
redirect("summary.php","POST");
In your php script, access it like
<?php
error_reporting(E_ALL);//show all errors and notices
$id = $_POST['id'];//you forgot the $ sign
//for debugging, check the post array
print_r($_POST);
?>
EDIT:
Make sure the obj.id is not null
That's not how you pass the data. value is a property of a form's input element, not the form itself.
So remove the line form.value = data; and replace with
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);
Now you should be able to get $_POST['id'].

Cannot specify the filename of exported excel file through javascript and php

I am using this function to export html tables to excel files.
Everything is working great except the filename....
When I am using this function the file name become something like FFE2dfA and its diferrent each time I am executing it...
Can you help me please how to specify the filename?
This is the function:
function toExcel(){
var tab_text="<html xmlns='http://www.w3.org/1999/xhtml' lang='el-GR' lang='el-GR'>";
var tab_text=tab_text+"<?php Response.AddHeader("Content-Disposition", "inline;filename=filename.xls") ?>";
var tab_text=tab_text+"<meta http-equiv='content-type' content='text/plain; charset=UTF-8'/>";
var tab_text=tab_text+"<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('table_results'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");
tab_text= tab_text.replace(/<img[^>]*>/gi,"");
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, "");
tab_text= tab_text.replace(/<button[^>]*>|<\/button>/gi, "");
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
sa = window.open('data:application/vnd.ms-excel,filename=filename.xls,' + encodeURIComponent(tab_text));
return (sa);
}
here in your code:
var tab_text=tab_text+"<?php Response.AddHeader("Content-Disposition", "inline;filename=filename.xls") ?>";
everything looks good, until javascript reaches Content-Disposition
which confuses javascript, it expects either an operator like + or an end of the line ; indicator, instead there is an unexpected identifier Content which in javascript’s eyes is an stranger!
I think what you meant is:
"<?php Response.AddHeader(\"Content-Disposition, inline;filename=\"filename.xls\"\") ?>"

html2canvas.js not capturing image for dynamically generated content

I am using vivagraphs to generate dynamic svg element but when I click capture button, no nodes and edges are shown.
This is the script:
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
$('#btn').click(function(){
html2canvas($("#graph1"), {
onrendered: function(canvas) {
var myImage = canvas.toDataURL("img/png");
window.open(myImage);
}
});
});
While I inspect for elements svg is shown after rendering graph but snapshot does not contain nodes and edges.
Is there an alternative for html2canvas or can I fix this issue?
if you want to save the image from canvas to some image format here is some help for you. hope this will help you out.
$(document).ready(function() {
$('#btn').click(function(){
html2canvas(document.getElementById('graph1'), {
onrendered: function(canvas) {
var cs = new CanvasSaver('save_img.php',canvas,'myimage')
}
});
});
});
here CanvasSaver() function define is here below which take three parameters one is a php file which process image from RAW date to some image format. i'll write the code of 'save_img.php' belwo this script part and save that file in your root directory.
function CanvasSaver(url, cnvs, fname) {
this.url = url;
if(!cnvs || !url) return;
fname = fname || 'picture';
var data = cnvs.toDataURL("image/png");
data = data.substr(data.indexOf(',') + 1).toString();
var dataInput = document.createElement("input") ;
dataInput.setAttribute("name", 'imgdata') ;
dataInput.setAttribute("value", data);
dataInput.setAttribute("type", "hidden");
var nameInput = document.createElement("input") ;
nameInput.setAttribute("name", 'name') ;
nameInput.setAttribute("value", fname + '.jpg');
var myForm = document.createElement("form");
myForm.method = 'post';
myForm.action = url;
myForm.appendChild(dataInput);
myForm.appendChild(nameInput);
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
in above script whatever the image formate you want to save from browser give that image extension in this function above script
nameInput.setAttribute("value", fname + '.jpg');
now here is the code for your 'save_img.php' and save it in your root directory.
<?php
# we are a PNG image
header('Content-type: image/png');
# we are an attachment (eg download), and we have a name
header('Content-Disposition: attachment; filename="' . $_POST['name'] .'"');
#capture, replace any spaces w/ plusses, and decode
$encoded = $_POST['imgdata'];
$encoded = str_replace(' ', '+', $encoded);
$decoded = base64_decode($encoded);
#write decoded data
echo $decoded;
?>
you maybe using beta version of lib , goto releases on github page of html2canvas and download stable alpha version

PHP and javascript combining variables issue

I have a PHP file where I display a html table (HTML) with data from a mysql table.
<?php
include 'connexion.php';
session_start();
$idfirm = $_REQUEST['idfirm'];
$namefirm = $_REQUEST['namefirm'];
The rows in the table have the
<tr class="clickableRow"...
Then on row click (javascript) I want to be able to call (POST) another PHP file that will display other information based on some info from the table row.
I have difficulties in achieving this.
What I have done so far is:
echo '
...
jQuery(document).ready(function($) {
$(".clickableRow").click(function() {
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
// So I can access the field data either like this
var myID = $.trim(tableData[0]);
// or like this:
var name = $(this).closest(\'tr\').find(\'td:eq(1)\').text();
alert(myID);';
echo" // here I would need to access some variables that I received above in PHP from POST
var namefirmx = '{$namefirm}';
var idfirmx = '{$idfirm}';
";
// and here I would like to call another PHP file (with POST) that will display info about the employee
So, how can I make a POST to another php file and send POST variables:name,namefirmx, idfirmx,myID
I am not sure how to make the POST.
I believe there is no other way to call the POST but javascript. (Remember that the POST must be made on row click)
Please help me out here...
Quick example of php script, some html tags are missed, but I think you will get a picture:
<?php
print_r($_POST);
?>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function($) {
$(".clickableRow").click(function() {
$(this).find("form").submit();
});
});
</script>
<table border="1">
<tr class="clickableRow">
<td>
<form method="post"><input type="hidden" name="p1" value="v1"><input type="hidden" name="p2" value="v2"></form>
v1
</td>
<td>v2</td>
</tr>
</table>
I solved my problem using a SO previous question. I am not sure what to do with this question.
Anyway, the answer is: adding a function in javascript, and calling it with my variables.
The function is:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
You can always add php variables inside your js code like the following :
<?php
$x="ABC";
?>
<script language="javascript">
jsX="<?php echo $x;?>";
alert(jsX);
</script>

Categories