Save textarea data from HTML page to a TXT file - javascript

I am building a database server for an organization that I am a member of, and one of the options is that they need to be able to change a list of names. This list is in a txt file located in the webroot.
I have loaded the txt file content in a textarea in an html page, and now what I need to be able to do is to save the textarea content to the same file, in case we need to update or change the names.
I have tried this:
<textarea id="toroq" style="width: 100%; height: 200px;"><?php include("lista_toroq.txt") ?></textarea>
<input id="save_toroq" type="button" value="Save" onclick="WriteToFile();"/>
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var text=document.getElementById("toroq").innerText;
//var fileName=document.getElementById("TextArea2").innerText;
var s = fso.CreateTextFile("lista_toroq.txt", true);
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
the problem is that it is not saving the file

JavaScript is not able to edit or make changes directly to files stored on the web server without having some form of code running.
Using something like this:
<?php
if ($_POST["text"]) {
file_put_contents("file.txt", $_POST["text"]);
}
?>
The above code runs when $_POST["text"] has been set.
Change your HTML form to something like this:
<html>
<body>
<form method="POST">
<textarea name="text tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You can store both of these bits of code in one PHP file. The result would be like this:
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>
<html>
<body>
<form method="POST">
<textarea name="text" tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>

You cant write directly from javascript. You have to use PHP to write. You can use file_get_contents to get file content and you can use file_get_contents to write.
You can do something like below with HTML form.
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>

Related

Transform GET request to POST request to load generated PDF file

In an html page I have a button that loads a generated pdf:
<button onclick='getpdf()'>GET PDF</button>
<script>
function getpdf(){
data={
var1: 'var1',
var2: 'var2'
};
window.open('genpdf.php?var1='+data['var1']+'&var2='+data['var2'], '_new');
}
</script>
genpdf.php is something like this:
<?php
require('fpdf/fpdf.php');
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
$pdf = new PDF();
/* ......... */
$pdf->Output('D','generated.pdf');
?>
My question is:
How can I change my code to pass parameters with POST method?
SOLUTION
ADyson suggested me this solution:
<form id="pdf" action="genpdf.php" methon="POST" target="_new">
<input type="hidden" name="var1" />
<input type="hidden" name="var2" />
<button onclick='getpdf()'>GET PDF</button>
</form>
<script>
function getpdf(){
$("#pdf input[name=var1]").val('var1');
$("#pdf input[name=var2]").val('var2');
$("#pdf").submit();
}
</script>
and
<?php
require('fpdf/fpdf.php');
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$pdf = new PDF();
/* ......... */
$pdf->Output('D','generated.pdf');
?>
and it works fine!
BUT
If I wanted to do that without the use of a form, how could I do?
If you want to implement without coding HTML then use following Javascript
var myform = document.createElement('form');
myform.style.display = "none";
myform.name='PdfGenOrSomethingElse';
myform.method='POST';
myform.action='genpdf.php';
myform.target='_blank';
var var1=document.createElement('input');
var1.type='text';
var1.name='var1';
var1.value='Put/update your value';
var var2=document.createElement('input');
var2.type='text';
var2.name='var2';
var2.value='Put/update your value';
myform.appendChild(var1);
myform.appendChild(var2);
document.body.appendChild(myform);
myform.submit();
Notice the form will not be displayed on the page. "display" property is set to "none".
You don't need any javascript function for this. Just use FORM element with action post:
<form action="genpdf.php" method="post" target="_blank">
<input type="text" name="var1" value="" />
<input type="text" name="var2" value="" />
<button type="submit ">GET PDF</button>
</form>
The don't forget to use $_POST instead of $_GET in your PHP script.

Pass PHP value to Javascript While They Are in Different Documents

I would like to create an upload form. In the form, member can upload multiple pictures to his/her own folder, which is named by the member's ID. For example, if the member's ID is 0001, then he/she can upload his pictures to image/0001/ folder.
In the uploading form, I use Javascript to let users upload multiple pictures in the same page. After user select the first picture, it generates the second <input type="file"> ; after selecting the 2nd picture, it generates the third <input type="file">.... and so on.
Now, I want to add constraint that each member can have at most 5 pictures in their folder. Therefore, I use a PHP variable $pic_in_folder to to count how many picture the member has already had in the his/her folder.
// test.js
$(document).ready(function(){
var pic_in_folder //To receive PHP variable $pic_in_folder
var blockCount = 1; //To count how many #upload_block.
$("body").on("change", "#picture", function(){
//if( pic_in_folder + blockCount < 5 ){
$("#upload_block" + blockCount ).after($("<div/>", {
id: "upload_block"+ (blockCount + 1),
class: "upload_block",
style: "margin: 1rem;"
}).fadeIn("slow").append($("<input/>", {
name: "picture[]",
type: "file",
id: "picture"
})));
blockCount += 1;
//}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Upload Picture</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/test.js"></script>
</head>
<body>
<?php
$member_Id = $_GET["member"];
$pic_in_folder = 0; //Count how many pictures this member currently have
foreach(glob("picture/".$member_Id."/*") as $file){
if(file_exists($file)){
$pic_in_folder += 1;
}
}
?>
<h3>You currently have <?php echo $pic_in_folder; ?> pictures.</h3>
<hr/>
<form name="upload_form">
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<input type="file" name="picture[]" id="picture" />
</div>
<input type="submit" />
</form>
</body>
</html>
For the Javascript codes, in order to avoid member having more than 5 pictures after they uploading pictures, I use variable pic_in_folder to get values from PHP variable $pic_in_folder ; blockCount to count how many input block is showing in the form. And the Javascript only generates input block when (pic_in_folder + blockCount) < 5
However, My HTML & PHP codes are in one document and the Javascript is in the other one. How can I pass the $pic_in_folder to the Javascript document variables ?
Thank you very much !!
You can declare the Variable for JS in your PHP-File:
echo '<script>var pic_in_folder = ' . $pic_in_folder . '</script>';
This will make it available globally. Then you can just use pic_in_folder in your other JS file. But be sure to include your external JS AFTER you did the script-tag above, so the external file actually knows about the variable.
Regarding best practices, I'm not sure if this is a good approach but it worked for me in one of my projects. Hope it helps :)
You can create a hidden field to store the $pic_in_folder value.
<input type="hidden" id="pic_in_folder" name="pic_in_folder" value="<?php echo $pic_in_folder;?>" />
Then read this value in JavaScript as follows:
var pic_in_folder = $("#pic_in_folder").val();
How about this?
<?php
$member_Id = $_GET["member"];
$pic_in_folder = 0; //Count how many pictures this member currently have
foreach(glob("picture/".$member_Id."/*") as $file){
if(file_exists($file)){
$pic_in_folder += 1;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Picture</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function picsInFolder() { return <?= $pic_in_folder;?>; }
</script>
<script src="/test.js"></script>
</head>
<body>
<h3>You currently have <?php echo $pic_in_folder; ?> pictures.</h3>
<hr/>
<form name="upload_form">
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<input type="file" name="picture[]" id="picture" />
</div>
<input type="submit" />
</form>
</body>
</html>
Then in your JS file you can call picsInFolder();
var pic_in_folder = picsInFolder();

checking isset at bottom of page not working

I have a dilemma (which I am yet to find a way around). For some reason, PHP doesn't want to check if $_POST["login"] at the bottom of the <body> tag within my document.
It will work if it is put at the very top of the document, or even the top of the <body> tag. However, if I put it at the top of the document / <body> tag, the output JavaScript will not execute!
For example, this is the document (where the PHP will not execute):
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
If I am to do something like this, however (the PHP will execute):
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
But due to how JavaScript compiles, it will throw an error saying how it cannot set a style on a null element.
I have no idea how to get around this dilemma, so all help is appreciated!
Cheers.
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_GET["login"])){
echo "<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('example-element').style.display = 'block';
}, false);
</script>";
}
?>
Check if this works..... I've added the display code inside the DOMContentLoaded event and change the $_POST variable to $_GET. Works fine in my local system.
You can do it as follows
<style>
.someClass {
display: block;
}
</style>
<?php
if(isset($_POST["login"])){
$hasClass = true;
}
?>
<form method="post">
<span id="example-element" class=<?php if(isset($hasClass)==true) echo "someClass"; ?> >Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
The other problem with your code is that you are not setting method of your form and by default it is GET where as in php you were looking for POST request.
You could solve it either by using $_REQUEST in php when you are not sure about the method.
Actally php executes before javascript.
Change like this
<script>
var isSubmit = "<?php isset($_POST['login'])?true:false; ?>";
if(isSubmit){
document.getElementById('example-element').style.display = 'block';
}
</script>"

Loading Effect using JS and PHP

I am working on a project in PHP and AIML where the bot replies to the user queries asked by a user through a microphone. I am new to jQuery and JS so I need help in implementing loading effect in between the user input and final output.
<?php
$display = "";
$thisFile = __FILE__;
if (!file_exists('../../config/global_config.php'));
require_once ('../../config/global_config.php');
require_once ('../chatbot/conversation_start.php');
$get_vars = (!empty($_GET)) ? filter_input_array(INPUT_GET) : array();
$post_vars = (!empty($_POST)) ? filter_input_array(INPUT_POST) : array();
$form_vars = array_merge($post_vars, $get_vars); // POST overrides and overwrites GET
$bot_id = (!empty($form_vars['bot_id'])) ? $form_vars['bot_id'] : 1;
$say = (!empty($form_vars['say'])) ? $form_vars['say'] : '';
$convo_id = session_id();
$format = (!empty($form_vars['format'])) ? $form_vars['format'] : 'html';
?>
<!DOCTYPE html>
<html>
<head>
<title>Interact With Sia</title>
<script src="jquery.js"></script>
<script type="text/javascript" src="talk.js"></script>
</head>
<body onload='document.getElementById("say").focus(); document.getElementById("btn_say").style.display="none";'>
<center>
<h3>Talk to Sia</h3>
<form id="chatform1" name="chatform" method="post" action="index.php#end" >
<!-- <label for="say">Say:</label> -->
<input type="text" name="say" id="say" size="70" onmouseover="startDictation()" style="color:red" />
<input type="submit" class="say" name="submit" id="btn_say" value="say" />
<script>
$('#say').trigger('mouseover');
</script>
<input type="hidden" name="convo_id" id="convo_id" value="<?php echo $convo_id;?>" />
<input type="hidden" name="bot_id" id="bot_id" value="<?php echo $bot_id;?>" />
<input type="hidden" name="format" id="format" value="<?php echo $format;?>" />
</form>
<br/><br/>
<?php echo $display; ?> //THIS DISPLAYS THE OUTPUT TO THE QUERY
</center>
</body>
</html>
As soon as the page loads, the microphone in the user's browser is activated [via talk.js_startDictation()] and after the user finishes the voice input, the query is sent to the scripts and then the result is diplayed by <?php echo $display; ?>.
How can I implement a loading effect in place of <?php echo $display; ?> until the script returns the result of the query and updates the $display variable on the page?
You could use AJAX to archieve this, like:
1 - Load jquery.js (you could use CDN or download it).
2 - Create a div with a loader (usually a gif is fine, there are a lot). Hidde it with css: display:hidden;
3 - Add at the bottom of your page:
<script>
// Attach a submit handler to the form
$( "#chatform1" ).submit(function( event ) {
// Start the loader
$('#loader').show();
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var data = $(this).serialize();
var url = "urlToYourPhpFile.php";
// Send the data using post
var posting = $.post( url, { data: data } );
// Put the results in a div
posting.done(function( dataResponse ) {
//do something with dataResponse
$('#loader').hide();
});
});
</script>
When the form is sumitted, jquery 'catch' the request, process the .submit() functions and send the data via post to a .php file (you should create it) and receive the params with $_POST. Something like:
yourPhpFile.php
<?php
$convo_id = $data['convo_id'];
//do something
...
?>

How to save form/textarea to file with no file extension PHP

I am trying to pull a file in a textarea, edit it, then save the edited data to the same file. The submit function seems to go off, it posts the data, and in javascript console it returns the message "couldn't write values to file!", and in the original text area where it pulled the text from, it blanks out that file as if it overwrote the file with no information.
Am I using the wrong ID for my $data? (Textarea ID is edit, am presuming the information is coming from there).
I've used this same save setup on other .html pages, and am wondering if it is because I am saving to a file that has no file extension. If that is the issue, is there a way around that?
Maybe there is an issue elsewhere?
Snippet from my HTML page of the form area:
<form name="editorarea" method="post" action="/my/site/address/here/revotestingpdsave.php">
<textarea id="edit" style="width: 800px; height: 800px;">
<?php
$filevar = "/my/site/address/here/revotesting/actions";
$handle = fopen($filevar, "r");
$contents = fread($handle, filesize($filevar));
fclose($handle);
echo $contents;
?>
</textarea><p><input class="Save Button" type="submit" name="Save" value="Save" id="submit"></form></p></center>
And this is My Save Form PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['edit'];
if(get_magic_quotes_gpc()){
$data = stripslashes($data);}
$filevar = "/my/site/address/here/actions";
$fp = fopen($filevar, "w") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
echo "Saved to $filevar successfully!";
}
?>
<?php
// If this file is not on the server touch() will create it for you
$target = "/my/site/address/here/revotesting.cfg";
touch($target);
?>
to display the successful message on the same page just move the revotestingpdsave.php content to the same page so
<form method="post">
// rest of form
</form>
<?php
if(isset($_POST['edit'])) {
// add revotestingpdsave.php content here
}
?>
$_POST['edit'] is being sent empty, then it's being written to the file making it empty, just add name attribute to the textarea, like this:
<textarea id="edit" name="edit" style="width: 800px; height: 800px;">

Categories

Resources