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.
Related
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
A bit of background, I mainly work in .Net/C# and never did any PHP my whole life and my company gave me an existing PHP code and asked me add some feature to it.
The webpage I need to work on is a catering system. The page recalculates the total price when there are changes to the number of pax. This worked fine if every item in the menu is similarly priced.
function RefreshPrice() {
menuid = getQueryString('menuid');
$.ajax({
url: "ajax.php",
type: "POST",
data: {
refreshprice: "refreshprice",
menuid: menuid,
},
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
But now there are items that cost more than others, so I need to recalculate on each item selection. I'm trying to use a hidden field to store the additional price for the item.
<input type="checkbox" class="validate-checkbox" item-name="<?php echo $item["Name"];?>"
name="menuitem[]" value="<?php echo $item["Id"];?>">
<input type="hidden" class="addprice" name="addprice" value="<?php echo $item["AddPrice"];?>">
But how do I get the values of the hidden field of each selected item so I can do something like this.
function RefreshPrice() {
menuid = getQueryString('menuid');
addprice= document.getElementsByClassName("addprice:checked").val(); //OR $(".addprice:checked").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: {
refreshprice: "refreshprice",
menuid: menuid,
addprice: addprice,
},
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
Sorry if this is a duplicate question, but most answer I found were using form submit POST method and got them using $_POST["addprice"], but this is manually constructing the ajax POST.
I think its not a good idea to store values in hidden form fields. because for security reasons user can modify your old values.
my suggestion is, you should send form value to your PHP and make a DB call and compare the values again. if you found the changes then update value otherwise leave it.
As I'm sure you've realized it is a security issue to calculate prices from data that can be altered on the client-side. Also, if the server-side is simply there to add the values, why not handle it directly in the javascript.
either way, the code below should collect data values of the checked items.
<input type="checkbox" class="validate-checkbox priceItems" item-name="<?php echo $item['Name'];?>" name="menuitem[]" value="<?php echo $item['Id'];?>" data-price="<?php echo $item['AddPrice'];?>">
you can add prices as a parameter to the data of the ajax function or do the sum here.
var prices = $('.priceItems:checked').map(function() {
return $(this).data('price');
}).get();
After doing some research and lots of testing I found a way to achieve what you desire so here is an example of it...
I've been testing this example on an app that I am building so the example will not be using your code, but the method is the same, you will just need to adjust it to work with your code...
Okay so first let's create the needed table and populate it with few rows
PHP
// Establish Connection (change the connection details if necessary)
$mysqli = new mysqli ('localhost','root','','test');
// Create table
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS permissions(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL
)");
// Populate table
mysqli_query($mysqli, "INSERT INTO permissions (
name,
description
) VALUES (
'manage_users',
'Can add/edit users'
),
('permission_plus',
'Can manage roles/permissions & access logs'
)");
?>
So, in this example I will be trying to create a new role for my web office and assign the role some of the existing permissions and to achieve that we will need to create a form that will display all of the existing roles from the table that we have just created...
HTML
<!--Make sure to include JQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<div id="addRole">
<form method="POST" id="addroles">
<input type="text" id="rolename" placeholder="Role Name" />
<input type="text" id="role_description" placeholder="Role Description" />
<hr /><span class="title">Include Permissions</span>
<div id="checks">
<?php
$query = mysqli_query($mysqli, "SELECT * FROM permissions");
while($row = $query->fetch_assoc()){
$permid = $row['id'];
$permname = $row['name'];
$permdesc = $row['description'];
echo "<label class='checks' title='$permdesc'>
<input type='checkbox' class='selected' data-id='$permid'/>
$permname</label>";
}
?>
</div>
<input type="submit" value="Add Role" />
</form>
</div>
Now, after we have the form displaying all the rows from the "permissions" table in a form of a checkbox, we can finally come to the most important part of the code, which is storing the selected checkboxes in an array using JavaScript/JQuery and passing them on to the server using AJAX...
JavaScript
$('#addroles').on('submit', function(event){
event.preventDefault();
let rolename = $('#rolename').val();
let roledesc = $('#role_description').val();
let permissions = [];
$('.selected').each(function(){
if($(this).is(":checked")){
permissions.push($(this).data('id'));
}
});
if(rolename != '' && roledesc != ''){
$.ajax({
url: 'addrole.php',
method: 'POST',
data: {
rolename: rolename,
roledesc: roledesc,
permissions: permissions
},
success: function(data){
console.log(data);
}
});
}
});
As you can see, the script here says, after you submit the form, first prevent it from it's default function and assign the values from the form fields to this specific variables, and when it comes to the checkboxes, create an array and then for each checked checkbox - push the value stored in data-id inside the previously created array, then fire AJAX and pass on all the variables to the server and after the server handles the data, please tell us what it said
addrole.php
$mysqli = new mysqli ('localhost','root','','test');
$permissions = $_POST['permissions'];
foreach($permissions as $permission){
echo $permission.' ';
}
The server breaks down the passed array of selected checkboxes using a foreach function and echoes the value stored in the data-id of each selected checkbox and we can see the result of it in our browser's console.
Here is some CSS for the sake of the appearance of this example
CSS
#addRole{
background-color: rgb(241, 241, 241);
position: relative;
width:30%;
padding:20px;
}
#addRole input[type='text']{
width:80%;
height:40px;
margin:5px 5px 5px 0px;
position: relative;
left:50%;
transform: translate(-50%);
text-align: center;
outline:none;
}#addRole input[type='submit']{
width:80%;
height:40px;
margin:5px 5px 5px 0px;
position: relative;
left:50%;
transform: translate(-50%);
text-align: center;
outline:none;
}
#addRole form hr{
width:30%;
margin-bottom: 20px;
margin-top: 20px;
}
.checks{
display: inline-block;
padding:20px;
text-indent: -20px;
background-color: rgb(252, 252, 252);
border:1px solid rgb(238, 238, 238);
margin: auto;
}
#checks{
position: relative;
left:50%;
transform: translate(-50%);
margin:10px;
display: flex-box;
text-align: center;
}
#addRole input[type='checkbox']{
width:20px;
height:20px;
margin:0px 0px 0px 20px;
outline:none;
text-align: center;
}
.title{
position:relative;
left:50%;
transform: translate(-50%);
text-align: center;
display: inline-block;
font-size: 20px;
margin:auto;
margin-bottom: 10px;
}
I'm brand new to Svelte (3.0+)...and for my latest project, I'd like to emulate the functionality of many "todo" lists that allow you to edit todo items previously submitted by double-clicking on them (Here's an example of the functionality I'm looking for).
I imagine, the first step is figuring out how to make a div contentEditable with Svelte with the on:dblclick event handler. I'm having trouble figuring out the syntax for this task (though I can do it with vanilla javascript).
Here's the Svelte code I have so far: ( Here it is on CodeSandBox.io - see page: CEDiv.svelte)
<script>
function edit(event) {
//update db functionality goes here
//alert("you've 'submitted' your edit")
}
function handleDblClick() {
//I need help HERE...and probably on the div on:dblclick down below....
}
function handleKeydown() {
key = event.key;
keyCode = event.keyCode;
//submit the div's content to the edit function if enter or tab is pressed.
keyCode == 13 || keyCode == 9 ? edit(event) : null;
}
</script>
<style>
div.read-mode {
padding:10px;
border:1px solid green;
height:30px;
line-height:30px;
width:500px;
margin:0 auto;
}
div.edit-mode {
padding:10px;
background: lightgreen;
border:3px solid green;
height:26px;
line-height:26px;
width:496px;
margin:0 auto;
}
</style>
<div on:dblclick={handleDblClick} class="read-mode" on:keydown={handleKeydown} contentEditable="false">
I want this Div to be editable one double click.
</div>
Thanks in advance for your help!
Add a boolean variable
let editable = false;
which will be changed inside your handler
function handleDblClick(event) {
editable = true; // or use editable=!editable to toggle
}
bind your editable variable inside the attribute,
and take a look how to dynamically toggle the class "edit-mode" using a ternary operator
<div
on:dblclick={handleDblClick}
class={editable ? 'edit-mode': 'read-mode'}
on:keydown={handleKeydown}
contenteditable={editable}>
I want this Div to be editable on double click.
</div>
Here's a CodeSandbox fork
I'm still learning JS and jQuery, so don't hate on my coding too much! :P
Anyways, here's what I am trying to do:
I have a database that has all cities and postal codes for a country.
Some postal codes have multiple cities.
I am first making an auto-complete for the postal code being entered that shows the cities for that postal code in an absolute positioned div. The div is created by a jQuery append to show all of the cities for that postal code. That is all working fine.
Once I have the div showing the cities, when I click on a city name, it needs to move the name of that city to the ShipCity input box, then a separate function clears the div and hides it.
But this is where I'm running in to issues.
Since I'm using a jQuery append to make the div, all the divs created have the same id. I can get the City input box to show a city name, but it only grabs the first one from the append, and not the one I am actually clicking on.
I have been working on this for 3 days now and am getting frustrated that I am this close but I can't complete it. :o
I hope this makes sense. Any help is appreciated.
Here is the code:
Also, this is run from an .hta, and php is not an option. Has to be strictly css/html/js.
-CSS
#container {
padding:2;
color:black;
border-spacing:0px;
margin:1px;
width:400px;
height:400px;
white-space:nowrap;
float:left;
}
#container label {
width:100px;
padding:0;
color:black;
float:left;
font-weight:bold;
margin-right:5px;
display:table-cell;
}
#container input {
width:170px;
padding:0;
color:black;
margin-left:5px;
text-transform:uppercase;
}
#hiddenDiv {
display:none;
position:absolute;
border:1px solid;
top:418px;
left:580px;
width:250px;
background-color:#FFCC00;
}
-JS
window.onload = function() {
// autocomplete : this is executed every time we change the text.
$( "#ShipZip" ).keyup(function() {
var min_length = 3; // min caracters to display the autocomplete
var keyword = $('#ShipZip').val();
if (keyword.length >= min_length) {
// do something as we type
var recCountry = document.em.ShipCtry.value;
var recZip = document.em.ShipZip.value;
c = new ActiveXObject("ADODB.Connection");
var strConn = "provider=sqloledb;data source=server\\name;database=name;uid=username;pwd=password";
c.Open(strConn);
var r = new ActiveXObject("ADODB.Recordset");
var r2 = new ActiveXObject("ADODB.Recordset");
var strQuery = "SELECT city_name, country_division_code FROM city_postarea WHERE '"+recZip+"' BETWEEN postcode_from AND postcode_to AND country_code='"+recCountry+"' ORDER BY city_name";
var strCntQuery = "SELECT COUNT(city_name) as cnt FROM city_postarea WHERE '"+recZip+"' BETWEEN postcode_from AND postcode_to AND country_code='"+recCountry+"'";
r.Open(strQuery, c);
r2.Open(strCntQuery, c);
if(r2.fields("cnt")>1) {
while (!r.EOF) {
var cityname=r.fields('city_name').value;
$("#hiddenDiv").append('<div class="popUp" id="zippy" name="'+recZip+'">'+recZip+', '+cityname+'</div>');
$("#hiddenDiv").css("display", "block");
r.movenext();
}
}
close.strConn;
} else {
// hide city list
$('#hiddenDiv').empty();
$('#hiddenDiv').hide();
}
})
// this function will be executed when we select an item
$('#hiddenDiv').click(function() {
// change input value
dog=$("#zippy").html();
dog=dog.split(", ").pop();
$('#ShipCity').val(dog);
// hide the popup
$('#hiddenDiv').empty();
$('#hiddenDiv').hide();
});
}
-HTML
<div id='hiddenDiv'>
</div>
<label>Zip: <span class='ast' style='color:#FF0000'>*</span></label>
<input name='ShipZip' class='input' type='text' id='ShipZip' /><br />
<label>City: <font color='#FF0000'>*</font></label>
<input name='ShipCity' class='input' type='text' id='ShipCity' /><br />
So I fixed it by this beautiful, simple, one line of code...
city=$(this).attr("id");
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/