I am facing some difficulties while get the proper code to show the session timeout count down in the progress bar in my html page.
Can any one help me in doing this.
Thanks
I searched over internet and found one example on how can be this done. Here is one simple example - $inactive variable is session expiracy time, e.g. 600 seconds):
function start_onload(){
var expire_time = new Date().getTime() + 1000*<?php echo $inactive; ?>;
countdown_session_timeout();
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
var timeout_message = document.getElementById('timeout_message');
if (remaining>0) {
timeout_message.innerHTML = 'Session will expire in '+ Math.floor(remaining/60) + ' min. ' + (remaining%60) + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Session expired.';
}
}
}
Php script here: http://pastebin.com/Dik0hyYd (those sessions are only as example.)
Related
I'm failing to save the info to when a logged in user clicks on the favorite button.
This is my first week in javascript class(including ajax). We're allowed to copy paste as long as we understand the process. So the first thing I did was looking up tutorials as to how to make favorite / unfavorite buttons and took over a template. Then I searched up how save the info in the database once the user clicks the favorite button. I'm not sure linking to external websites is allowed but I specifically took over this code:
<!DOCTYPE html>
<html>
<head>
<title>New page name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = new Array();
$(function(){
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
faves = myfaves;
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.title+'</h4> Open page '+
'Remove me';
$('#appendfavs').append(element);
});
});
</script>
</head>
<body>
Add me to fav
<ul id="appendfavs">
</ul>
</body>
</html>
It displays "add me to fav" like it's supposed to but then when I click on it, it returns:
(index):54 Uncaught TypeError: Cannot read property 'push' of null
at HTMLAnchorElement.<anonymous> ((index):54)
at HTMLBodyElement.dispatch (jquery.min.js:3)
at HTMLBodyElement.r.handle (jquery.min.js:3)
The assignment is as follows:
""- Show a 'favorite' icon / heart. Make this clickable via jQuery / JavaScript. If you click on it, an AJAX request must be sent with the blog post id. A WP plugin must 'process' the AJAX request, and store in the session (or database) that user X has liked a certain blog post. The server must return a JSON response."
Now had a small side question, for after I resolve the error of this thread, is my way of thinking correct:
Through CSS I'll create a heart button
This script itself does the ajax request with post ID
WP plugin I've done before
This script provides the JSON response
Thank you stack overflow in advance, I look forward to learning!
I have an epub3 book with 2 pages as well as a Table of Contents Page. I am viewing this book in Apple's Books, their inbuilt epub3 reader, on Mac OSX. The two pages appear side by side. The first page is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=500, height=600"/>
</head>
<body>
<p id="result"></p>
<script>
//<![CDATA[
var current_page = "1";
var other_page = "2";
var t = 0;
setInterval(function() {
var d = new Date();
var storage = localStorage;
storage.setItem("t"+ current_page, d.toLocaleString());
document.getElementById("result").innerHTML = storage.getItem("t"+ current_page) +" "+storage.getItem("t"+ other_page);
}, 1000);
//]]>
</script>
</body>
</html>
and the only thing different in my second page is:
var current_page = "2";
var other_page = "1";
So every second, Page 1 saves the current time to Local Storage as t1, and Page 2 does the same for the value t2. At the same time, both pages are reading both t1 and t2 from Local Storage, before their values are displayed to screen. However in ibooks, Page 1 only manages to display the current value for t2 when the page is reloaded - like when I flip to the Table of Contents and then back to Page 1 and 2 again. With something similar happening for Page 2 with regard to t1.
So at time 21:10:00, Page 1 might display:
08/09/19, 21:09:18 08/09/19, 21:08:58
and Page 2:
08/09/19, 21:09:22 08/09/19, 21:08:01
I also tried using Session Data but Page 1 can't ever read t2 and Page 2 can't read t1. So, this would be displayed instead:
08/09/19, 21:09:18 null
I can think of several applications where it would be very useful for Pages to communicate with each other.
For example, if a video is playing on one page, it would be useful to stop it if a video on another page is started. This would normally be done using Session Storage. This is related to my own use case and the reason I started exploring this problem.
Likewise, if the user is asked on Page 1 to enters the name of the main character of the story, then that entry should appear immediately on Page 2 once it is entered.
Is there any other way for Pages to communicate with each other in epub3 other than Local or Session Storage?
I dont know epub3 and dont have a MAC to test, but here are four possible solutions that come to my mind:
Cookies
It is not as performant as localStorage for that use-case, but if you dont have many options, better that than nothing.
Functions to create, read and delete cookies (Credits to https://stackoverflow.com/a/28230846/9150652):
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;';
}
Usage for your example:
<script>
//<![CDATA[
var current_page = "1";
var other_page = "2";
var t = 0;
setInterval(function() {
var d = new Date();
setCookie("t"+ current_page, d.toLocaleString(), 100); // 100 days
document.getElementById("result").innerHTML = getCookie("t"+ current_page) +" "+getCookie("t"+ other_page);
}, 1000);
//]]>
</script>
BroadcastChannel
BroadcastChannel is a very new functionality, so it might not be supported by the "Books" app. But here is a concept:
<script>
//<![CDATA[
var broadcaster = new BroadcastChannel('test');
var current_page = "1";
var other_page = "2";
var t = 0;
setInterval(function() {
var d = new Date();
// Send message to all other tabs with BroadcastChannel('test')
bc.postMessage({
senderPage: "t"+ current_page,
date: d.toLocaleString()
});
}, 1000);
broadcaster.onmessage = (result) => {
if(result.senderPage == "t"+ other_page) { // If the message is from the other page
// Set HTML to current date + sent Date from other page
var d = new Date();
document.getElementById("result").innerHTML = d.toLocaleString() +" "+result.date;
}
};
//]]>
</script>
Some sort of Backend
If none of the above works, you probably have no other option, than to use some sort of backend, to provide and save the data
If it is just for you, I suggest you to use a free tier of Firebase or MongoDB Atlas, as they both provide quite some value on their free tier.
If you do it with a Backend, it could be done with something like this:
<script>
//<![CDATA[
var current_page = "1";
var other_page = "2";
var lastLocalDate = new Date();
const serverUrl = "http://someUrl.com/endpoint/"
// Gets the latest date of the other page via ajax
function getUpdate() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
// If successful, update HTML
if (xmlhttp.status == 200) {
document.getElementById("result").innerHTML = lastLocalDate.toLocaleString() +" "+xhr.responseText;
}
// Update the date of this page anyways
sendUpdate();
}
};
// GET request with parameter requestingPage, which is the other page
xmlhttp.open("GET", serverUrl, true);
xmlhttp.send(`requestingPage=${other_page}`);
}
// Sends the current date of this page to the webserver
function sendUpdate() {
var xmlhttp = new XMLHttpRequest();
// No need to check if successful, just update the page again
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
getUpdate();
}
};
lastLocalDate = new Date();
// POST request with parameters page and date
xmlhttp.open("POST", serverUrl, true);
xmlhttp.send(`sendingPage=${current_page}&data=${lastLocalDate.toLocaleString()}`);
}
// Start with sending an update (so that lastLocalDate is at least sent once to the server)
sendUpdate();
//]]>
</script>
And some methods in your backend that need to look something like this (note that this is not valid code in any language):
#GET
function getDate(requestingPageId)
find latest entry with page.id == requestingPageId
return page.date
#POST
function saveDate(savingPage, savingDate)
store new page element with
page.id = savingPage
page.date = savingDate
And a collection in your database looking like this:
[
{
id: 1,
date: "date"
},{
id: 2,
date: "date"
},{
id: 2,
date: "date"
},{
id: 1,
date: "date"
},
// ...
]
Window References
If the Books app opens the second tab from the first tab, it might be worth to look into:
Window.postMessage()
With its functions:
Window.open()
to open the second tab and get a reference to it
And Window.opener to get a reference to the opener
I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}
This question already has answers here:
Using AJAX to dynamically update text from a database
(2 answers)
Closed 5 years ago.
I try javascript typing game by nikola. Here is the link codepen.io/nikola1970/pen/oxXbmb and When the time's up i want to post the points i get to the score table on my database.
CREATE TABLE public.score
(
id bigserial,
score integer,
user character varying(50),
"timestamp" timestamp without time zone,
)
how can i do?
I add the countdown function like this.
function countdown() {
points = 0;
var timer = setInterval(function(){
button.disabled = true;
seconds--;
temp.innerHTML = seconds;
if (seconds === 0) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "ajax.php?points=" + points , true);
xmlhttp.send();
// return false;
alert("Game over! Your score is " + points);
//Done!
scoreDiv.innerHTML = "0";
words.innerHTML = "";
button.disabled = false;
clearInterval(timer);
seconds = 60;
timerDiv.innerHTML = "60";
button.disabled = false;
}
}, 10);
}
and here is my ajax.php
<?php
session_start();
include("config.php");
$score = $_GET['points'];
$user = $_SESSION['id'];
$query = pg_query(" insert into t_score (score, id_user, timestamp) values ('$score', $user, 'now()') ") ;
pg_close()
?>
i've editted my countdown function and ajax.php. now it's work to send the score to the database.
You're going to need some server-side code to process incoming data and stick it in your database. PHP, Django/Python, and Ruby on Rails are all good choices. You could then write an AJAX function in the javascript that sends the score data to the server when the game is over.
Okay so I'm trying to set a JavaScript document to a variable in PHP?
Essentially I'm setting the WiFi speed I calculate in a Javascript document to a variable,so I can save the variable value in a database with other information as an instance.
The Javascript code is pretty long so I don't know if I should copy the whole code in and set it equal to the variable or if there's a syntax to set it to a variable.
I've seen:
<script type="text/javascript" src="file.js"></script>
Online for calling a Javascript file but not sure how to get that value and store it in a variable.
You could do something like this
$js = file_get_contents( 'http://www.example.com/javacsript.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $js));
echo $value;
Hope this will help you
The JavaScript must be executed in the browser client. The flow would be:
PHP generates HTML (wich includes the JS code)
HTML is sent to the browser
The browser renders the HTML and executes the JS
The browser communicates with the server to tell the result
Depending if the JS is a library or an script the precise steps would differ. But basically inside tags you will have to save the result to a variable and then make an AJAX call (easier with jQuery.ajax() ) to communicate that variable to the server and then the server can do something with it.
I hope that helps puting you on the right track. If you expand the info in your question, I will try to update my answer :)
You have to do this using a POST, possibly to the same PHP script.
<form method='post' id=myform>
<input type=hidden id=js-to-php value=0>
</form>
<script>
jQuery(document).ready(function(){
//calulcate the wifispeed using the long js code
//then save it in the field
$('#js-to-php').val(YOUR_SPEED);
// send the form
$('#myform').submit();
});
</script>
and then in the same script:
if( isset($_POST['js-to-wifi']) && $_POST['js-to-wifi']!='') {
// store your stuff in DB
}
So here is the Java script code:
//Source: http://stackoverflow.com/questions/5529718/how-to-detect-internet-speed-in-javascript
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg";
var downloadSize = 4995374; //bytes
window.onload = function() {
var oProgress = document.getElementById("progress");
oProgress.innerHTML = "Loading the image, please wait...";
window.setTimeout(MeasureConnectionSpeed, 1);
};
function MeasureConnectionSpeed() {
var oProgress = document.getElementById("progress");
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}
download.onerror = function (err, msg) {
oProgress.innerHTML = "Invalid image, or error downloading";
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;
function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
oProgress.innerHTML = "Your connection speed is: <br />" +
speedBps + " bps<br />" +
speedKbps + " kbps<br />" +
speedMbps + " Mbps<br />";
}
}
I want to get the value that this will return (I will edit the code so I am only getting one value) and then place it inside a php variable. The issue is when I run it on a webpage after using:
$Speed = file_get_contents( 'wiFiCalc.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $Speed));
echo $value;
I just get the code on the html page, as clami219 stated above. I just want to return that value to print it and store it in the database.
Also, Jobst, the way you wrote was kind of hard to follow. I am using a form action in my html code to go to the speed so it can be stored in the database before it returns to the next HTML page so could you explain how your code works?