Synchronize text area in html - javascript

I am creating a simple web application in which whatever the client types on textarea field also appears
on the server side textarea field at the same time.
Imagine it as 2 tabs In one tab user writes on text area and on the other tab user sees the whatever the user has typed at the same time.
Below is the two jsp files code snippet
client.jsp
<%
code=request.getParameter("code_area");
out.print(code);
try
{
File file=new File("code");
if(file.exists())
{
BufferedWriter bw=new BufferedWriter(new FileWriter(file));
bw.write(code);
bw.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<form action="client.jsp">
<textarea name="code_area"> <%=code%> <textarea>
</form>
server.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Server</title>
<%#page import="java.io.*"%>
<script>
setTimeout("location.reload(true);",1000);
</script>
</head>
<body>
<%
InputStreamReader reader=new InputStreamReader(new FileInputStream("code"));
BufferedReader in=new BufferedReader(reader);
String s;
while((s=in.readLine())!=null)
out.print(s);
%>
</body>
</html>
In other Words whatever the user types on the textarea field in the client side appears on the server side at the same time.
The solution that i thought for this problem ..
I created a common file so that whatever user types on textarea in client gets saved in the file and the server side reads from the text-file at the same time.
But sadly i am not able to code it..Because of the problems i am facing in this ..
Everytime i save a file the cursor in the textarea gets to the beginning of the line which i dont want to happen...?
In order to save the data into text file i need to click on submit button ...Auto submit
which i tried from this example http://www.formget.com/javascript-auto-submit-form/# is not working ....
Can somebody help me to tackle this problem ??
Any help would be highly appreciated ...

My new understanding (through comments) of the question is... There is a teacher who wants to see all the imputs of the students in real time, each student has 1 input area and the teacher has an display of each students input but can not edit them.
We will create 2 HTML documnet sand 2 PHP APIs. The first HTML document is for the student to enter their name and then a text area for them to enter an answer. The second HTML documnet will be for the teacher to view all the answers. The first API will be for the students to submit their answer (after each keypress ~real time). And the second API will be for the teacher to retrieve all the students answers (with a small refresh interval to simulate real time without having to use WebSockets).
Also you should create a directory/folder within this directory/folder named "answers" and if you are are Mac/Linux give permissions 0777 to the "answers" directory/folder.
Student.html
<html>
<head>
<title>Student</title>
<script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
<script>
$(function () {
$("#answer").on("keyup", function (e) {
$.post("sendAnswer.php", {name: $("#name").val(), answer: e.target.value}, function(){console.log(arguments)});
});
$("#name").on("blur", function(e){
if(e.target.value.length>0)
$("#answer").attr("disabled", false);
});
});
</script>
</head>
<body>
<label for='name'>Who are you?</label>
<input type='text' id='name' Placeholder='Name' />
<br><br>
<textarea id='answer' placeholder='Answer' disabled></textarea>
</body>
</html>
Teacher.html
<html>
<head>
<title>Teacher</title>
<script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
<script>
$(function(){
refresh_answers();
window.setInterval(refresh_answers, 500); // Refresh Every 500ms (0.5 seconds)
});
function refresh_answers(){
$.get("getAnswers.php", function(x){
x = JSON.parse(x);
var s = ""; // HTML string
for(var i=0;i<x.length;i++){
s+="<div><span class='name'>"+x[i].name+"</span><span class='answer'>"+x[i].answer+"</span></div>";
}
$("#answers").html(s);
});
}
</script>
<style>
#answers div {
display: inline-block;
width: 256px;
height: 256px;
border: 1px solid black;
margin: 16px;
}
#answers .name {
display: block;
width: 256px;
height: 56px;
text-align: center;
font-size: 25px;
line-height: 56px;
font-weight: 700;
border-bottom: 1px solid black;
}
#answers .answer {
display: block;
padding: 16px;
font-size: 14px;
}
</style>
</head>
<body>
<div id='answers'></div>
</body>
</html>
sendAnswer.php
<?php
file_put_contents(dirname(__FILE__)."/answers/".$_POST['name'].".txt", $_POST['answer']);
?>
getAnswers.php
<?php
$answers = glob(dirname(__FILE__)."/answers/*");
$answers_array = array();
foreach($answers as $a){
$answer = array();
$answer['answer'] = file_get_contents($a);
$name = explode("/", $a);
$name = array_pop($name);
$name = str_replace(".txt", '', $name);
$answer['name'] = $name;
array_push($answers_array, $answer);
}
print_r(json_encode($answers_array));
?>

This can be done with WebSockets but that's way more complicated to set up, but it would be more proper and faster.
For an easy solution (without WebSockets), what you need to do is send an ajax POST request to the server every time the key is pressed, this might be really slow but it should work. Here I will be using jQuery on the client side and PHP on the server side.
HTML
<input id='input' />
JavaScript / jQuery
// After DOM ready
$(function(){
// When a character is entered in the input
$("#input").on("keyup", function(e){
// Send the inputs value to the server
$.post("saveInput.php" {text: e.target.value});
});
});
PHP (saveInput.php)
<?php
file_put_contents("input.text", $_POST['text']);
?>
This should save their input into a text file called input.txt on the server every time they enter a character in the input.

Take a look at this plugin I think it will do what you want:
https://togetherjs.com/

Related

Why does the entire php script reload on button press?

I am working on a simple web page that stores the start time, then displays the time when you click a button sort of like a timer. I came across this problem where when clicking a button in a form, it reloads the script overwriting the start time variable. Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Work Tracker</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {background-color: grey;}
.button {
border: none;
color: rgb(0, 0, 0);
padding: 15px 32px;
text-align: right;
text-decoration: none;
display: inline-block;
font-size: 25px;
margin: 4px 2px;
cursor: pointer;
border-radius: 10px;
}
.button2 {background-color: #ff0000;}
#text1 {
color: black;
text-align: center;
font: bold 24px sans-serif;
background: white;
padding: 10px;
border: solid black 2px;
border-radius: 10px;
}
</style>
</head>
<body>
<?php
date_default_timezone_set('America/Los_Angeles');
$startTime = date("h:i a");
echo "<h2>" . $startTime . "</h2>";
if (isset($_POST["btn-endtimer"])) {
$endtime = date("h:i a");
echo "<h2>" . $endtime . "</h2>";
}
?>
<script type="text/javascript">
if(starttime === undefined){
var starttime = "<?php echo "$startTime"; ?>";
console.log(starttime);
}
console.log(starttime);
</script>
<form method="post">
<input type="submit" value="End Timer" name="btn-endtimer" style="background-color:#ffb3b3; height:100px; width:250px; font-size:50px; border-radius: 15px; border-color: #fc9f9f">
</form>
</body>
</html>
Here is the webpage:
it displays the time when the page was opened as well as a button. When this button is clicked, it runs a line of code that stores the current date, but it reloads the script, so the start time variable is overwritten to the current time. Is there a way to send the starttime variable somewhere so that it can not be changed? This is what is looks like after clicking the button a few minutes later:
Update: I have tried session variables, but it seems that the code jumps straight there. For example:
session_start();
echo $_SESSION['a'];
$_SESSION['a'] = "hello world"
echo $_SESSION['a'];
prints
hello world
hello world
Why?
Perhaps the easiest way to interact between browser and server to do what you want
( log a time ) would be to use AJAX. Requests are sent without needing to reload the page and provide a better user experience.
The following would send a time to the server (same page in this instance) - how you deal with that server-side is not specified but would, in most cases, involve writing to a database.
This demo will fire an ajax request but due to the sandbox will throw an error but inspecting network traffic in console should illustrate what happens.
// utility to format a Date into a minimal timestring - chose UK for locale
const gettime=()=>Intl.DateTimeFormat('en-GB', { timeStyle:'medium' } ).format( new Date() );
// utility to display, in the H2 element, the time at any particular moment
const displaytime=()=>{
let date=gettime();
let content=`<div>${date}</div>`;
document.querySelector('h2').insertAdjacentHTML('beforeend',content)
};
// the AJAX callback. This can be used to do what ever you need to do once you have logged
// the time on the server. DOM manipulation, inform user, open window etc
const callback=(r)=>{
alert(r)
};
// There is no need to actually send the time from the client ( it can be modified )
// - instead you could just send a beacon to say "log now" type thing but for example
// send the time to the same page.
const sendtime=()=>{
let url=location.href; // or /path/to/script.php etc
let fd=new FormData();
fd.set('time',gettime() );
fetch( url,{ method:'post',body:fd } )
.then(r=>r.text())
.then(callback)
.catch(alert)
};
// delegated event listener to respond to button clicks
document.addEventListener('click',e=>{
if( e.target instanceof HTMLInputElement && e.target.type=='button' && e.target.name=='btn-endtimer' ){
displaytime();
sendtime();
}
});
// how initial load time - this could be fetched from db rather than using current time!
displaytime();
body {
background-color: grey;
}
/*
other styles removed as they were not applicable
to the original code
*/
input[name="btn-endtimer"] {
background-color: #ffb3b3;
height: 100px;
width: 250px;
font-size: 50px;
border-radius: 15px;
border-color: #fc9f9f
}
<h2></h2>
<input type="button" value="End Timer" name="btn-endtimer" />
The method post will always refresh the page since PHP code is sent to server and it needs to be loaded typically on new page.
You can avoid that by using JavaScript function
<body>
<?php
date_default_timezone_set('America/Los_Angeles');
$startTime = date("h:i a");
echo "<h2>" . $startTime . "</h2>";
?>
<script>
window.addEventListener("load", function() {
var endTime = "";
var startTime = "<?php echo $startTime; ?>";
console.log(startTime);
document.getElementById("end-timer-button").addEventListener("click", function() {
endTime = new Date().toLocaleTimeString();
document.getElementById("end-time").innerHTML = endTime;
});
});
</script>
<button id="end-timer-button"
style="background-color:#ffb3b3; height:100px; width:250px; font-size:50px; border-radius: 15px; border-color: #fc9f9f">End
Timer</button>
<h2 id="end-time"></h2>
</body>
The PHP code is used to create new variable $startTime and store it. The JavaScript code is used to handle the button click and store var = EndTime wich is an empty string that gets value from PHP $startTime. Finally document.getElementById("end-time").innerHTML = endTime; prints out the EndTime variable into <h2 id="end-time"></h2> if you want the time to be displayed above the button. you can simply put it between the PHP code And start of JavaScript like this
echo "<h2>" . $startTime . "</h2>";
?>
<h2 id="end-time"></h2>
<script>
Hope this helps / solves your problem

Posting a variable in a php file

i've created 3 files. The main is html with javascript, the second one is based on php only and the third one uses html and inline php forms.
In main file, i've written the below script:
$(document).on('click', '.print_fumes_card', function(){
var user_id1 = $(this).attr("id");
alert(user_id1);
$.ajax({
url:"print/print_fumes_card.php",
method:"POST",
data:{user_id1:user_id1},
success:function(data)
{
window.open ("print/print_fumes_card.php","_blank");
}
})
});
The above script is enabled, only when i press the button '.print_fumes_card' in second php file.
The problem is that var user_id1 doesn't pass to third file (mix of html and php) "print_fumes_card.php" and i can't undertand why.
I need that variable in 3rd file to, execute some select queries.
The structure of thrid file is the following:
<!DOCTYPE html>
<?php
require 'conn.php';
echo $_POST["user_id1"];
?>
<html lang="en">
<head>
<style>
.table {
width: 100%;
margin-bottom: 20px;
}
.table-striped tbody > tr:nth-child(odd) > td,
.table-striped tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
#media print{
#print {
display:none;
}
}
#media print {
#PrintButton {
display: none;
}
}
#page {
size: auto; /* auto is the initial value */
margin: 10; /* this affects the margin in the printer settings */
}
</style>
<link rel="stylesheet" href="style4.css" media="all" />
</head>
<body>
<header class="clearfix">
<div id="logo">
<img src="logo1.png">
</div>
<div id="company">
<h2 class="name">App</h2>
<div>address</div>
<div>phone</div>
<div>email</div>
<div>web</div>
</div>
</div>
</header>
<main>
<div id="details" class="clearfix">
<div id="client">
<div class="to">Plate:</div>
<div class="address"><?php
require 'conn.php';
$result = $conn->query("SELECT * FROM vehicles WHERE plate=(SELECT plate FROM visits WHERE vid='".$_POST["user_id1"]."')");
$row = mysqli_fetch_array($result);
echo $row['plate'];
?></div>
</div>
....
....
..
.
.
The problem is that $_POST["user_id"] variable isn't recognized as in second file, which is only php. Is there any special technique to pass that variable in third file?
I've tried different combinations and i can't figure out what i'm missing.
The two separate requests to print/print_fumes_card.php make little sense based on the information provided. The initial ajax post passes only user_id1 and does not appear to be attempting to make any change to the data. The second request does not pass the param at all. Just pass the param in the window.open call -
$(document).on('click', '.print_fumes_card', function(){
var user_id1 = $(this).attr("id");
alert(user_id1);
window.open ('print/print_fumes_card.php?user_id1=' + user_id1, '_blank');
});
And then -
<?php
require 'conn.php';
echo $_GET['user_id1'];
?>
The comment about understanding the SQL Injection vulnerabilities and using prepared statements still stands. At the very least you should force the type -
$user_id1 = (int) $_GET['user_id1'];

modified javascript code unable to be saved

I'm working on a hangman game using html, css, js and php.
Using php you get a random word from a xampp mysql server in an unordered display.
By using javascript, input boxes are automatically created depending on the length of the word.
After filling all input boxes a submit button appears.
The problem is that before implementing php functionality to get an item from the DB I was testing my app only with js with a given word var word = "Rhodes" . After implementing php and managing to display a randomized word from the DB in my screen and modifying my js code I also got the word ="Rhodes" next to my random word and only input boxes corresponding to "Rhodes" length instead of the new word .
In other words the code I deleted still runs like it was never
modified .
I have my new code below . With js I get the php word to create input boxes . It doesn't work and the old code is displayed .
function hangman(){
var island = document.getElementById("random-island"); //the given word that is supposed to be found
createSpaces(island);
const inputLists = document.querySelectorAll("input");
document.querySelectorAll("input").forEach(el => {
el.addEventListener('input', evt => {
const showButton = [...inputLists].filter(ip => ip.value.trim() !== '').length === inputLists.length;
document.getElementById('submitbtn').style.display = showButton ? 'block' : 'none';
});
});
}
function createSpaces(text){
for(var i=0;i<text.length;i++){
var space = document.createElement("input");
space.setAttribute("class" , "dash");
document.getElementById("hangman-container").appendChild(space);
}
}
.transparent-box {
border:none;
position:absolute;
top:10%;
left:15%;
background-color:black;
height:500px;
width:70%;
opacity: 0.6;
}
.transparent-box p {
color:white;
text-align:center;
}
.transparent-box h1 {
color:white;
position: relative;
text-align:center;
font-size:20px;
top:30px;
}
#hangman-container {
position: relative;
width:auto;
top:30%;
left:0%;
background-color: transparent;
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.dash {
margin:0;
padding:20px;
align-items: flex-start;
width:4%;
border:none;
border-radius: 5%;
background-color: turquoise;
color:red;
font-size:40px;
}
.dash:focus {
opacity:0.8;
}
#submitbtn {
display: none;
position: absolute;
top:200%;
left:80%;
float:right;
}
<body onload = hangman()>
<div class = "transparent-box" id = "t-box">
<p>Play here </p>
<h1 id = "hidden-word">The word is :
<?php
$link = #mysqli_connect('localhost' , 'root' , 'password' ,'dbname');
if(!$link){
echo 'Error connecting to DB';
exit;
}
$query = "SELECT island_name FROM dodecanese ORDER BY RAND() LIMIT 1";
$result = #mysqli_query($link, $query);
if(!$result){
echo 'There is an issue with the DB';
exit;
}
$row = #mysqli_fetch_assoc($result);
echo '<span id = "random-island">'.str_shuffle($row['island_name']). '</span>';
?>
</h1>
<form id = "hangman-container" method="POST">
<button type = "submit" class = "hide" id="submitbtn">Submit</button>
</form>
</div>
</body>
I would appreciate your help with this . Thank you in advance .
I do not fully understand what your actual question is.
But if I understood correctly - you would like PHP to play a role in this game.
(i.e. PHP to connect to the database instead of javascript doing everything itself by having a big list of words in the array, pick it up, doing checks all in client-side).
Then what I would suggest having at least 3 files (not mentioning assets):
Index.html
NewWordGenerator.php
WordChecker.php
Additionally, I would suggest you to spend some time if possible familiarising with ajax. jQuery might give you an easier entry point for ajax.
Suggested workflow:
Index.html file that has a start button, js + ajax code, placeholders, styling etc.
When a visitor would press "start the game" button, it would trigger ajax to make a call to NewWordGenerator.php file which would connect to the database and get any random word from your database, which would be displayed in index.html when ajax is successful, js to "cut" the word into letters and put it to placeholders/form etc.
When a player would click submit button, javascript/jQuery would prevent default form submission, send user input via ajax to WordChecker.php which would be handling checking the word and giving the result that is returned and displayed in index.html.
Hope that makes sense.

Save logs from form into a txt file

form {position: absolute; left: 45%; top: 35%;}
#email {position: relative;left: 30%;bottom: 90%;text-shadow:1px 1px #D8E3EC;color: #097BDA;}
#password {position: relative;left: 25%;bottom: 100%;text-shadow:1px 1px #D8E3EC;color: #097BDA;}
#submit {position: absolute;bottom: -30%;left: -30%;text-shadow:1px 1px #D8E3EC;padding: 0.5% 25%;border-radius: 2px;background-color: #31A1FF;border-width: 4px;border-color: #0468BB;}
#submit:hover{background-color: #67BAFF;}
#eee {border-radius: 5px;}
#ppp {border-radius: 5px;}
#titlu {position: absolute;left: 31.5%;text-shadow:2px 2px #F9FBFC;font-family: fantasy;color: #097BDA;}
body {background-image: url(background.jpg);}
#tran {opacity: 0.9;position: absolute;left: 37%;top: 20%;;width: 30px 30px;}
<!DOCTYPE HTML>
<html>
<head>
<title>Website</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<img id="tran" src="tran.jpg">
<h1 id="titlu">Welcome,please login to get free games right now!</h1>
<form class="formm" action="form.php" method="get">
<p id="email">Email</p>
<input id="eee" type="email" placeholder="Put your email here"><br />
<p id="password">Password</p>
<input id="ppp" type="password" placeholder="Put your password here"> <br />
<input id="submit" type="submit" value="GET YOUR FREE GAME NOW!">
</form>
</body>
</html>
So I want to add something like - when I put my email and password and press submit button, to get the logs into another file, like logs.txt.
In PHP is really simple creating files and writing something into them. If you want write a log every time someone submits your form, you just need to call this function :
<?php
function write_log($string) {
$log_file = 'log.txt';
$string .= PHP_EOL;
if ($fh = #fopen($log_file, "a+")) {
fputs($fh, $string, strlen($string));
fclose($fh);
return true;
} else {
return false;
}
}
?>
Naturally it must exists a file called 'log.txt' to write in. If it extists, you just need to call this function setting your log content as the string parameter. Here is an example :
<?
//Write "Hello World" into your log.txt file.
write_log("Hello World");
?>
What does PHP_EOL do?
PHP_EOL is a constant the simply find the best method to break a line in the system you're using. So that you can insert multiple lines formatted in a great schema without do anything.
References
http://php.net/manual/en/reserved.constants.php
http://php.net/manual/en/function.fputs.php
Javascript can't write to a log.txt file unless you use scripting.FileSystemObject which is an ActiveX and runs with IE only. I would suggest to use console.log() to make it happen or call a webservice to write the log in other end.
Update: If you are flexible, nodeJs can provide you a solution with filesystem
var fs = require('fs');
fs.appendFile('log.txt', 'Log text data to append', function (err) {
if (err) throw err;
console.log('Log updated');
});

Why are the links and text disappearing from from this UL on my webpage?

Full disclosure, this is an assignment from an advanced JS class I'm taking. I've been trying to figure this out for a couple of weekends and it's driving me crazy! I'm far more familiar with jQuery than I am straight JS (which is one of the reasons I'm taking this class).
The webpage is supposed to take input from the user to create a <UL> list of links with some other strings associated that are related to the link. That part works just fine, what I can't figure out is why as soon as I'm done clicking on the Add Link button, the new link shows very briefly, then disappears! If I click the button very quickly, I can get several of them to show up, but as soon as I stop, all of them disappear.
I tried making a fiddle out of this, but clicking on the Add Link button gave me a POST error (which may be a clue to it's behavior?). If you cut & paste the code into an HTML file & run it, you'll see the behavior I'm describing.
I thought it had something to do with the init() function, so I tried running that at the bottom of the <body>, but that didn't make any difference. I also tried running it without an init, but couldn't figure out how to get the onclick listener initialized, even if it ran at the bottom of the <body>. I notice that even though I'm defining the favesList in global scope, it's still showing up as undefined after it should have been initialized with values (at least from my point of view). However, it looks like it's going out of scope instead which doesn't make sense to me. Console.log isn't providing me the reason why it's disappearing, or I haven't figured out a way to log the event.
I'm reasonably certain I'm missing a fundamental thing (like it's going out of scope for some reason?), so if someone could point out what that thing is I'd be grateful (I also don't need a definitive answer, just a nudge in the right direction, this is basically homework and I know I'm supposed to be figuring this out on my own, but I think a couple of Sundays of my time is giving it the college try).
Here's the code:
<!doctype html>
<html>
<head>
<title>Advanced JavaScript Project: Favorites and Tags</title>
<meta charset="utf-8">
<style>
body {
font-family: Helvetica, Ariel, sans-serif;
}
form {
display: table;
border-spacing: 5px;
width: 40%;
}
form p {
display: table-row;
}
form label {
display: table-cell;
text-align: right;
}
form input {
display: table-cell;
width: 95%;
}
span.comment {
font-size: 80%;
color: #777777;
}
span.tags {
font-size: 80%;
color: rgb(48, 99, 170);
}
#submit {
width: 20%;
}
</style>
<script>
window.onload = init;
var favesList;
console.log(favesList);
function init() {
//get submit button handle
var submit = document.getElementById("submit");
//add click handler to button to call method to add text to the list
submit.onclick = AddFavorite;
console.log("back in init");
}
function favorite(url, title, comment, tags){
console.log(this);
this.url = url;
this.title = title;
this.comment = comment;
this.tags = tags;
console.log(this);
}
function AddFavorite(){
var f = new favorite(
document.getElementById("url").value,
document.getElementById("title").value,
document.getElementById("comment").value,
document.getElementById("tags").value);
console.log(f);
favesList = document.getElementById("list");
console.log(favesList);
var node = document.createElement("LI");
var a = document.createElement('a');
a.appendChild(document.createTextNode(f.title));
a.href = f.url;
console.log(a);
node.appendChild(a);
node.appendChild(document.createTextNode(f.comment));
node.appendChild(document.createTextNode(f.tags));
console.log(node);
favesList.appendChild(node);
console.log(favesList);
}
</script>
</head>
<body>
<h1>Tag and save your favorites</h1>
<form id="form">
<fieldset>
<legend>Add a new favorite:</legend>
<label for="url">URL:</label>
<span><input id="url" type="url" placeholder="http://www.cnn.com" value="http://www.cnn.com"></span><br>
<label for="title">Title:</label>
<input id="title" type="text" value="CNN World News"><br>
<label for="comment">Comment:</label>
<input id="comment" type="textarea" value="Thoughts?"><br>
<label for="tags">Tags:</label>
<input id="tags" type="text" value="Enter keywords separated by commas"><br>
<input id="submit" type="submit" value="Add Link">
</fieldset>
</form>
<br>
<h1>List of favorites</h1>
<ul id="list"></ul>
</body>
</html>
You need to return false; as the last line in your AddFavorite() method, to stop the browser from processing the button and refreshing the page.

Categories