How to countdown timer based on database column value - javascript

There are not many solutions/tutorials on how user inserted value in database could be used as a dynamic timer countdown that does not reset after the page is refreshed.
I'm facing a problem where the value is displayed but static. Is there any other way of implementing this?
database & web
How could I add functionality to redirect or stop the countdown timer?
index.php
<?php
session_start();
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'root';
$dbName = 'student';
$conn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName,$conn);
$duration="";
$query="select duration from table1";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)){
$duration=$row["duration"];
}
$_SESSION["duration"]=$duration;
$_SESSION["start_time"]=date("Y-m-d H:i:s");
$end_time=$end_time=date('Y-m-d H:i:s',strtotime('+'.$_SESSION["duration"].'minutes',strtotime($_SESSION["start_time"])));
$_SESSION["end_time"]=$end_time;
include_once 'response.php';
?>
<div id="response"> </div>
<script type="text/javascript">
setInterval(function()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","response.php",false);
xmlhtpp.send(null);
document.getElementById("response").innerHTML=xmlhttp.responseText;
},1000);
</script>
response.php
<?php
$from_start=date('Y-m-d H:i:s');
$to_end=$_SESSION["end_time"];
$first=strtotime($from_start);
$second=strtotime($to_end);
$differenceinseconds=$second-$first;
echo gmdate("H:i:s",$differenceinseconds);
?>

I ran your code and found a couple issues:
There is a JavaScript error
This is because there is a typo in the Javascript code on the following line:
xmlhtpp.send(null);
Change that to
xmlhttp.send(null);
And the Asynchronous requests should execute properly.
The line include_once 'response.php'; will have the effect of echoing the formatted date string above the <div>, which will yield two formatted timestamps when the AJAX requests are running. Remove that include_once line to avoid that scenario.
The code for response.php doesn't call session_start();. Unless your error handler settings are such that E_NOTICE errors are ignored, there will likely be an error message at the top of the timer:
E_NOTICE : type 8 -- Undefined variable: _SESSION -- at line 12
See a demonstration in this phpFiddle.

Related

JS script that reacts to PHP script

I have such a request: I have to do JS script, that works with PHP script.
Right now i have such a PHP code:
~~~~~~ PHP ~~~~~~
<?php
$email = filter_input(INPUT_POST, 'email');
if (!empty($email)){
$host = "localhost";
$dbusername ="root";
$dbpassword ="";
$dbname = "email";
$conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
if (mysqli_connect_error()){
die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else{
$sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
if ($conn->query($sql)){
echo "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
else{
echo "<script type='text/javascript'>alert(\"Your email is already in our subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
$conn->close();
}}else{
echo "<script type='text/javascript'>alert(\"Don't forget to include your email address !\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
?>
And here is a challenge. Instead of currently js scripts in php (that they activate on clean page without any content) JS script has to work on page, without reload - on the same page, when the request was sent from. I don't know how to do that ( i'm quite new to JS ) and i hope for your hints
Thanks for advices
If you don't want to reload the rendered page, you will have to work the other way around: not PHP is generating the whole page, but a JS script is pulling information from a PHP script and uses this information to display the according note.
There are multiple ways to fetch information from a server using JavaScript, the most prominent being AJAX to load HTML chunks or JSON responses. Please search for those topics as this is a relatively broad topic and your question is much too broad as it is.

PHP login algorithm not redirecting to next page (unsure on connection to database)

I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.

use json and javascript to populate a table

I'm using php to fetch a db query that I want to make a table from. I want to put the query results into a json object and then use javascript from there to output the results into a table. I used json_encode to create the json object in php.
I'm fairly new to javascript so I'm a little confused as to how I can send the json object I've created to javascript and then output the results using javascript? Should I include the javascript in the same file as the php page or a different one?
If you can explain what you're doing that would be awesome because I really want to know what's going on at each step.
Here's what I have so far:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
Update:
So I went ahead and made xyz.php my backend page and made a main.php for displaying the results. I started off with this sample function to make sure my jquery was fetching the results from the xyz.php page. Now, I don't know how to display the results in a table using jquery.
Here's what I did for my main.php page:
<?php
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("xyz.php");
});
});
</script>
<div id="div1"></div>
<button>Show JSON Results</button>
What you can do is:
Make the PHP file as backend. So that,
xyz.php:
// PUT YOUR CODE HERE
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
AND it should be accessible from the URL.
For example: xyz.php?id=2000
Now, on the page from where you want to populate this data, use jQuery
$.post
And manipulate this json.
This will ensure your page loads faster as dynamic data is getting populated after initial page load.
Hope it works for you.

Mysql database not updating when PHP script executes

I have a timeout function that runs correctly except for one thing. The field that checks if a user is currently logged in does not update once the script runs. I was testing it all week and got it to actually work, but when I tried to test it today, I stopped updating the field. Can anyone explain why? I also have a logout button that does a jQuery call which runs a logout.php script when the button is clicked which works perfectly. Could this be why the timeout script has stopped updating the database? I don't think that could what it is, but I could be wrong.
timeout script(php)
<?php
require("../includes/header.php");
$now = time();
$expires = $_SESSION["expire"] + 30;
$user = $_SESSION["id"];
if(!isset($_SESSION["expire"]) || $expires > $now){
$_SESSION["expire"] = $now;
}
else{
mysqli_query($connect, "UPDATE `$user_table` SET `logged_in`=0 WHERE `user_id`='$user_id'");
session_unset();
session_destroy();
mysqli_close($connect);
header("Location: timed_out.php");
}
?>
logout script(js & php)
$(document).ready(function(){
$("#logout").on("click", function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/logged_out.php");
}
}, "json");
})
})
logout script(php)
<?php
ob_start();
require("../includes/header.php");
$user_id = $_SESSION["id"];
ob_clean();
mysqli_query($connect, "UPDATE `$user_table` SET `logged_in`=0 WHERE `user_id`='$user_id'");
session_unset();
session_destroy();
mysqli_close($connect);
echo json_encode(array("success"=>1));
?>
Another question I have is. Would it be beneficial to do the timeout script in jQuery instead of PHP? If so, how would I go about doing that?
I think you need some simple debuggin ;)
Your login script says in the query:
WHERE `user_id`='$user_id'
but the code a bit higher says
$user = $_SESSION["id"];
That's NOT the same variable ;)

Generating AJAX callback- table on a javascript popup

I have used jquery ajax which initiates on click of a button , and on click of it a variable passes to the php script that the jquery post is using. However when i try to append the return data on javascript alert() method it returns the php script's html contents instead rather than rendering it out. Can anyone assit me on this?
<?php
$var = $_POST['var'];
$sql = mysql_query("select * from racers Where style = '$var'");
while ($r = mysql_fetch_assoc($sql))
{
$name = $r['rName'];
echo '<tr><td>'.$name.'</td></tr>';
}
?>
You have a syntax error, try this;
<?php
$var = $_POST['var'];
$sql = mysql_query("select * from racers Where style = '$var'");
while ($r = mysql_fetch_assoc($sql))
{
$name = $r['rName'];
echo '<tr><td>'.$name.'</td></tr>';
}
?>
change sql_query to mysql_query
I assume you are using Apache (as most of the PHP configs do).
Did you check your Apache configuration. I guess it must be configured to process PHP's as scripts. Otherwise it returns it as it is without parsing

Categories