Why does the entire php script reload on button press? - javascript

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

Related

How to show Number of users connected in pubnub using presence and subscribe method

<!DOCTYPE html>
<html>
<head>
<title>Currently Active Demo</title>
<style type="text/css">
.currently-active {
position: fixed;
margin: 10px;
padding: 5px;
bottom: 0;
left: 0;
border: solid 1px #AFAFAF;
border-radius: 6px;
font-family: "Arial";
}
</style>
</head>
<body>
<div class="currently-active">
<span>Currently Active: </span><span id="active"></span>
</div>
</body>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.20.2.js"></script>
<script type="text/javascript">
var active = document.getElementById('active');
function setCurrentlyActiveUsers(numberOfUsers) {
active.innerText = numberOfUsers.toString();
}
setCurrentlyActiveUsers(1);
var pubnub = new PubNub({
publishKey: 'pub-demo',
subscribeKey: 'sub-demo',
heartbeatInterval: 30
});
pubnub.addListener({
presence: function(presenceEvent) {
console.log("Occupancy "+presenceEvent.occupancy);
console.log("Action "+presenceEvent.action);
setCurrentlyActiveUsers(presenceEvent.occupancy);
}
});
pubnub.subscribe({
channels: ['myWebPage1'],
withPresence: true
});
</script>
</html>
I have written a code to show the real-time total number of users connected in core JS using PubNub. But the problem I am facing is I am unable to get the accurate number. Sometimes When I have just executed the code I will get currently active user 0 and sometimes one. The problem lies in Presence action join and leave but I don't know how automatically sometimes I get presence action value as join and sometimes as leave and that too is random. Please help me resolve this issue so that I can get a concurrent number of active users who are connected in real-time and the number increase or decrease accordingly

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.

Is it possible for webpage to dynamically insert data from another file without needing a server call

Is it possible for webpage to dynamically insert data from another file without needing a server call?
What I mean by that is can a .html page update itself with something like XMLHttpRequest but instead of this making a call to a server just simply read in a file that is the same location as the html page.
Pseudocode
if(userclicks on x)
{
read and display contents of y within this div)
}
Background
I am converting an html report that currently uses a frameset divided into left and right panels. The left panel lists a series of folders that have been processed, the right-hand side shows the processing done on the selected folder.
I need to remove framset because outdated and not supported in html 5
iFrames not a suitable alternative as they are not designed for showing the content of an integral part of the site, they look plain weird when this is done.
It is not viable to preload all the content of the page and then uses javascript to hide/show the content of the file when user changes selection because the single html file would be too large and too slow to load.
It is not viable to make a call to a server because there is no server, the reports are created by an application and then can be viewed standalone without the application being run. They can also be sent to support to be viewed standalone.
My temporary solution is that when the user selects a file then the processing html file is displayed in a new tab (or window), but there is not a very satisfactory for the user
If I'm reading your question right, all of the necessary data is part of the page at the outset (since you can't load it from a server, it has to all already be there — but see under the line below for more on that). But you've said:
It is not viable to preload all the content of the page and then uses javascript to hide/show the content of the file when user changes selection because the single html file would be too large and too slow to load.
So that suggests the data itself is quite a bit smaller than the representation of the data.
You can certainly have an element on the page (for instance, a div) that you update with a rendering of a subset of the data the page holds, using the DOM. Here's a trivial example:
const data = [
{label: "one", a: "a one", b: "b one", c: "c one"},
{label: "two", a: "a two", b: "b two", c: "c two"},
{label: "three", a: "a three", b: "b three", c: "c three"},
{label: "four", a: "a four", b: "b four", c: "c four"}
];
function populateMenu() {
const menu = document.getElementById("menu");
for (let i = 0; i < data.length; ++i) {
const entry = data[i];
const a = document.createElement("a");
a.href = `#entry-${i}`;
a.textContent = entry.label;
a.addEventListener("click", event => {
event.preventDefault();
showEntry(entry);
});
menu.appendChild(a)
}
}
function showEntry(entry) {
const content = document.getElementById("content");
const {a, b, c} = entry;
content.textContent = `a: ${a}, b: ${b}, c: ${c}`;
}
populateMenu();
#menu a {
padding: 4px;
}
<div id="menu"></div>
<div id="content"></div>
That uses ES2015+ syntax, but you can do the same thing with ES5 only if you need to for your target environments.
The content div there can, of course, be the majority of the page display.
This is the basic nature of a single-page application (SPA), so further research using that term may be useful. But your SPA is standalone (whereas most will do server calls, but still update the page as above).
In a comment you've said:
Currently the files are created at the outset, there is the main folder and a file that represents the processing of each folder. The user could have processed a 1000 folders so that means the main file is essentially a list of 1000 folders, and then there are a 1000 other files each containing a few pages of data. SO clearly if we to combine of all of this into one file it would be about 1000 time larger, yet user would only eve be viewing the procesing associated with one folder...So your approach above would not work for me.
I'm afraid you're trying to have your cake and eat it. :-) Either you can load the data later, or it's all on the page at the outset. You said in the question you can't load the data later, so it must be in the page at the outset.
But: Your use of the word "files" above suggests that this report without a server can be a set of files, not just a single file.
Your cross-browser options if HTML File A needs to load content from HTML File B are:
Use iframes and update the src to go from file to file. You've said in the question that they "aren't for the main content of the page", but that's not my understanding; and that they're ugly, but they're completely stylable via CSS. They can literally be seamlessly integrated into the main page.
Keep using frames, update the src of the frame to move from file to file. Yes, frames were removed in HTML5. They will never be removed from web browsers, too much legacy.
Sadly, you can't reliably use XMLHttpRequest when your page is loaded from a file: URL. Some browsers allow it, others don't. (You can't use fetch in any of them, it specifically doesn't support the file: scheme.)
Your constraints literally constrain your choices, I'm afraid.
Here's an iframe example:
report.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Report</title>
<style>
#menu a {
padding: 4px;
}
#content {
border: none;
}
</style>
</head>
<body>
<div id="menu">
File 1
File 2
File 3
</div>
<iframe id="content" src="file1.html"></iframe>
<script>
document.getElementById("menu").addEventListener("click", event => {
event.preventDefault();
const a = event.target.closest("a");
document.getElementById("content").src = a.getAttribute("data-file");
});
</script>
</body>
</html>
file1.html (file2.html and file3.html are identical, just different names and numbers):
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>File 1</title>
</head>
<body>
This is file 1.
</body>
</html>
<template>
If you have local content on a file try using an <iframe> or a <template>. The latter is what we will consider. A <template> is inert and ignored by the browser so no matter how huge your extra content is -- it shouldn't be an issue.
Demo
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<style>
html {
font: 400 16px/1.5 'Consolas';
background: #000;
color: #fc0;
}
fieldset {
border-color: goldenrod;
border-radius: 8px;
}
input,
output {
display: block;
font: inherit;
}
[type=submit] {
float: right;
background: none;
color: gold;
border: 1px solid gold;
border-radius: 4px;
margin-top: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<form id='import'>
<fieldset>
<legend>Import data.html by <b>XMLHttpRequest()</b></legend>
<output id='content'></output>
</fieldset>
<input type="submit">
</form>
<template id='data'>
<style>{margin: 30px auto}table{table-layout: fixed;border: 3px solid cyan;width: 99%;border-radius: 6px}caption{font-size:1.2rem;color:gold}th{width: 33%;background: rgba(0,11,187,0.3);border: 1px solid rgba(0,11,187,0.7);color:#fc3}td{min-height: 30px;border: 2px ridge cornflowerblue;;color: yellow;background: none}
</style><section><table><caption>DATA</caption><thead><tr><th>TH</th><th>TH</th><th>TH</th></tr></thead><tbody><tr><td>TD</td><td>TD</td><td>TD</td></tr><tr><td>TD</td><td>TD</td><td>TD</td></tr><tr><td>TD</td><td>TD</td><td>TD</td></tr></tbody></table></section>
</template>
<script>
document.forms.import.onsubmit = getContent;
function getContent(e) {
e.preventDefault();
const destination = document.querySelector('#content');
const template = document.querySelector('#data');
const clone = document.importNode(template.content, true);
destination.appendChild(clone);
}
</script>
</body>
</html>
XMLHttpRequest()
Assuming that a separate web page on the same domain as the target web page is feasible it is possible to import HTML from another webpage (whether from a server or same domain) using XMLHttpRequest().
Demo Outline
Main page: index.html, Imported page: data.html
On main page the element that will have the imported HTML needs this:
<div data-x="data.html"...
Any type of element assigned data-x attribute with the value of the imported web page's URL.
Plunker
index.html
This Stack Snippet does not function because it loads an external page, for a working demo review this Plunker
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<style>
html {
font: 400 16px/1.5 'Consolas';
background: #000;
color: #fc0;
}
fieldset {
border-color: goldenrod;
border-radius: 8px;
}
input,
output {
display: block;
font: inherit;
}
[type=submit] {
float: right;
background: none;
color: gold;
border: 1px solid gold;
border-radius: 4px;
margin-top: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<form id='import'>
<fieldset>
<legend>Import data.html by <b>XMLHttpRequest()</b></legend>
<output data-x="data.html"></output>
</fieldset>
<input type="submit">
</form>
<script>
function xhr(e) {
e.preventDefault();
const tags = document.querySelectorAll("*");
let clone, file, xh;
for (let i = 0; i < tags.length; i++) {
if (tags[i].dataset.x) {
clone = tags[i].cloneNode(false);
file = tags[i].dataset.x;
xh = new XMLHttpRequest();
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
clone.innerHTML = xh.responseText;
tags[i].parentNode.replaceChild(clone, tags[i]);
xhr();
}
};
xh.open("GET", file, true);
xh.send();
return;
}
}
}
document.forms.import.addEventListener('submit', xhr);
</script>
</body>
</html>
data.html
This is just the plain web page that is imported to index.html, for a working demo, review this Plunker
<style>
section {
margin: 30px auto;
}
table {
table-layout: fixed;
border: 3px solid cyan;
width: 99%;
border-radius: 6px;
}
caption {
font-size:1.2rem;
color:gold;
}
th {
width: 33%;
background: rgba(0,11,187,0.3);
border: 1px solid rgba(0,11,187,0.7);
color:#fc3;
}
td {
min-height: 30px;
border: 2px ridge cornflowerblue;;
color: yellow;
background: none;
}
</style>
<section>
<table>
<caption>DATA</caption>
<thead>
<tr>
<th>TH</th>
<th>TH</th>
<th>TH</th>
</tr>
</thead>
<tbody>
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
</tbody>
</table>
</section>

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