Posting a variable in a php file - javascript

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'];

Related

Load external URL html on same page, needs to have navigation page1,2,3..., Cannot use iframes, tried using DIV'S but messes up external source's CSS

first time posting, i've searched, here's what I want to do, old implementation used iframe (had one iframe for the navigation, another for the URL) but no longer works with Chrome, cannot enable iframe's. The links are like this:
Here's what I've tried thanks to searching on the forum:
$(function(){
var $cur = $('#group .current');
var $items = $('#group .item');
function hideButtons() {
$cur = $('#group .current');
var index = $cur.index();
if(index > 0) {
$('#prev').show();
} else {
$('#prev').hide();
}
if(index < $items.length - 1) {
$('#next').show();
} else {
$('#next').hide();
}
}
hideButtons();
$('#next').click(function(){
$cur.next().addClass('current');
$cur.removeClass('current');
hideButtons();
});
$('#prev').click(function(){
$cur.prev().addClass('current');
$cur.removeClass('current');
hideButtons();
});
});
.container {
display: flex;
justify-content: center;
}
.center {
width: 800px;
height: 90%;
}
.item {
display: none;
}
.item.current {
display: block;
}
.rptButton
{
width: 80px;
}
.navButton
{
width: 90px;
}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="<%=request.getContextPath() %>/javax.faces.resource/jquery-1.7.2.min.js.xhtml?ln=javascripts"></script>
<style type="text/css">
</style>
</head>
<title></title>
<body >
<div style="text-align: center">
<button id="next" class="navButton">next</button>
<button style="display:none" id="prev" class="navButton">previous</button>
</div>
<div class="container" >
<div class="center" id="previewFrame" title="Preview Frame">
<div id="group" >
<!-- display page 1 no matter what-->
<div id="divIDNo1" class="current item">
<c:url value="<%=openURL%>" var="myURLCustom">
<c:param name="page" value="1" />
</c:url>
<c:import url="${myURLCustom}" />
</div>
<!-- display page 2 and so on-->
<c:forEach var = "i" begin = "2" end = "<%=numOfPages%>" varStatus="theCount">
<div id="divIDNo${theCount.index}" class="item" >
<c:import url="<%=openURL%>">
<c:param name="page" value="${i}"/></c:import>
</div>
</c:forEach>
</div>
</div>
</div>
</body>
</html>
This works but after page 1, the CSS of the source page messed up, fonts get larger, others smaller, lines disappear.
I have also tried loading the external pages, say 10 pages, with page breaks but the preview windows clumps the pages together even though the print option displays them correctly.
I've tried looking at MutationObserver but still a newbie at coding and don't know how to implement this.
The URL's are like this:
http://localhost:8080/viewDoc?entry=abc?page=1, then ?page=2, ?page=3,....
They need to load in the popup window, and then navigation (next, previous, first, last) to go to the next URL but popup window must stay open and only the content must change (page 1, 2, 3....)

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');
});

Alternative to hyperlinks with JqueryUI Mobile ListView

I have a page using JqueryUI Mobile. More specifically it uses JqueryMobile Lists
http://demos.jquerymobile.com/1.2.1/docs/lists/lists-ul.html
I love the look, feel, and usage of the listview, but I have come into a problem.
The users need to be able to click the link quickly, which is difficult with how I do it now. The link performs a PHP function, then redirects back to page they was on and the cycle restarts. Now that I am getting more familiar with AJAX, I would like to be able to have them click the link, it updates the database, then calls my AJAX script to update the data without the refreshing the page.
This would enable the users to be much much quicker with the tasks as most of the down time they have currently is the few seconds it takes to refresh (or more accurately be redirected back to) the page. When if its possible they would like to be able to click a link every second or even more if they are able to.
My question is: How can perform a database update based on dynamically generated links from a MySQLi database without requiring the user to refresh? I believe once I have that, I could also use Ajax to update the list every quarter second or so. I've considered using buttons, but I'm not sure how that would tie into listview, since listview seems to be only based on links.
On a side note - are their standard practices with often Ajax should update? Is there any guidelines I should follow?
Here is a sample of my current code:
<?php
session_start();
if(isset($_SESSION['username']))
{
}
else
{
$_SESSION['error']="You are logged in.";
header('Location: index.php');
exit;
}
?><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/> <!--320-->
<link rel="stylesheet" href="js/jquery.mobile-1.4.5.min.css">
<script src="js/jquery-1.11.3.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="js/jquery.mobile-1.4.5.min.js"></script>
<style>
.split-custom-wrapper {
/* position wrapper on the right of the listitem */
position: absolute;
right: 0;
top: 0;
height: 100%;
}
.split-custom-button {
position: relative;
float: right; /* allow multiple links stacked on the right */
height: 80%;
margin:10px;
min-width:3em;
/* remove boxshadow and border */
border:none;
moz-border-radius: 0;
webkit-border-radius: 0;
border-radius: 0;
moz-box-shadow: none;
webkit-box-shadow: none;
box-shadow: none;
}
.split-custom-button span.ui-btn-inner {
/* position icons in center of listitem*/
position: relative;
margin-top:50%;
margin-left:50%;
/* compensation for icon dimensions */
top:11px;
left:-12px;
height:40%; /* stay within boundaries of list item */
}
.ui-icon-delete:after{
background-color: #B22222 !important;
background-image:url("data:image/svg+xml;charset=US-ASCII,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22iso-8859-1%22%3F%3E%3C!DOCTYPE%20svg%20PUBLIC%20%22-%2F%2FW3C%2F%2FDTD%20SVG%201.1%2F%2FEN%22%20%22http%3A%2F%2Fwww.w3.org%2FGraphics%2FSVG%2F1.1%2FDTD%2Fsvg11.dtd%22%3E%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20%20width%3D%2214px%22%20height%3D%2214px%22%20viewBox%3D%220%200%2014%2014%22%20style%3D%22enable-background%3Anew%200%200%2014%2014%3B%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20fill%3D%22%23FFF%22%20points%3D%2214%2C3%2011%2C0%207%2C4%203%2C0%200%2C3%204%2C7%200%2C11%203%2C14%207%2C10%2011%2C14%2014%2C11%2010%2C7%20%22%2F%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3C%2Fsvg%3E")
}
.ui-icon-home:after{
background-color: #A2CD5A !important;
}
.ui-icon-arrow-u-r:after{
background-color: #3D59AB !important;
}
</style>
</header>
</head><center> <h2 style="">Empty For now<br><br>
</h2></center>
<a href="home.php" class="ui-btn ui-icon-home ui-btn-icon-left" data-ajax='false'>HOME</a>
<a href="ViewOrderMobile.php" class="ui-btn ui-icon-edit ui-btn-icon-left" data-ajax='false'>VIEW / EDIT CURRENT LINE</a>
<br><br><br><br>
<center><center>
<div data-role="main" class="ui-content"style="margin-top:-75px;">
<h2 style=""></h2>
<ul data-role="listview">
<?php
include "../../includes/databaseconnections/demo/database_connection.php";
///////////////////////////////////////////////////////////////////////////////////////////////
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else{}
$query = "SELECT * FROM Table1 LEFT JOIN Table2 USING (ID) WHERE Table1.feild1 = '0' ORDER BY dateSelected ASC LIMIT 25";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
if ($row['photoLink'] == NULL)
{
$row['photoLink'] = "endofgroup";
$row['lastName'] = "End Of Group " ;
$ID = "&ID=".$row['ID'];
}
if ($row[leftGym] == "1") { $flash = "style='color:#B22222;font-size:140%'";} else {$flash ="";}
echo "<li><a href='button1.php?sid=${row['ID']}' $flash style='font-size:140%;' width='25px' data-ajax='false'> {$row["lastName"]}, {$row["firstName"]} ({$row["pmBusNumber"]})</a><div class='split-custom-wrapper'>
<a href='button2.php?sID={$row['ID']}&lane=1{$ID}' data-role='button' class='split-custom-button' data-icon='delete' data-rel='dialog' data-theme='c' data-ajax='false' data-iconpos='notext'></a>
</div></li>";
}
/* free result set */
mysqli_free_result($result);
}
mysqli_close($link);
/////////////////////////////////////////////////////////////////////////////////
?>
</ul><br>
</div>
</div>
</div>
</body>
</html>
I've added comments to the code snippet. Please let us know if you require further info.
Based on jquery ajax() v3.1.1
html: update the a element in the list with class=myCustomClass
<a href='button1.php?sid=${row['ID']}' $flash style='font-size:140%;' width='25px' data-ajax='false' class='myCustomClass'> {$row["lastName"]}, {$row["firstName"]} ({$row["pmBusNumber"]})</a>
<div class='split-custom-wrapper'>
<a href='button2.php?sID={$row['ID']}&lane=1{$ID}' data-role='button' class='myCustomClass split-custom-button' data-icon='delete' data-rel='dialog' data-theme='c' data-ajax='false' data-iconpos='notext'>
</a>
</div>
<span id="status"></span>
script :
$(function () {
//Attach the click event to Links only with class=myCustomClass and perform this function
$("a[class=myCustomClass]").on('click', function (e) {
e.preventDefault(); //preven the page from navigating, the default behaviour for a link
$.ajax({
url : this.href, //perform a ajax request with the link, GET in this case
/* type: POST, */
beforeSend : function () {
$("#status").text('Working..')
}
}).done(function (data) {
console.log(data); //do something with the data if any
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("ERROR"); //report in console for errors
console.info(jqXHR);
console.info(textStatus);
console.info(errorThrown);
}).always(function () {
//do this step every time
$("#status").text('completed..')
console.info("completed"); irrespective of result
});
})

Synchronize text area in html

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/

Categories