How to update the PHP current timestamp using jquery/javascript every second - php

I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.

You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.

Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.

Related

using ajax to fetch a result from php and reload page

So I have been working on this for hours now, I have read a bunch of StackOverflow posts and I am still having no luck.
I have a page that has 2 sections to it, depending on the int in the database will depend on which section is being displayed at which time.
My goal is to have the page look to see if the database status has changed from the current one and if it has then refresh the page, if not then do nothing but re-run every 10 seconds.
I run PHP at the top of my page that gets the int from the database
$online_status = Online_status::find_by_id(1);
I then use HTML to load the status into something that jquery can access
<input type="hidden" id="statusID" value="<?php echo $online_status->status; ?>">
<span id="result"></span>
So at the bottom of my page, I added some jquery and ajax
$(document).ready(function(){
$(function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$newResult = $('#result').html(data);
window.setInterval(function(){
liveCheck();
}, 10000);
}
}
});
});
liveCheck();
});
this then goes to another PHP page that runs the following code
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
echo "<script>location.reload()&semi;</script>";
}else{
}
}
the jquery then loads into the HTML section with the id of "result" as shown earlier. I know this is a very bad way to do this, and as a result, it will work at the beginning but the longer you leave it on the page the slower the page gets, till it just freezes.
If anyone is able to point me towards a proper method I would be very grateful.
Thank you!!
js:
(function(){
function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(data.trim() == ''){
location.reload();
}else{
$('#result').html(data);
window.setTimeout(function(){
liveCheck();
}, 10000);
}
}
});
}
$(function(){
liveCheck();
});
})(jQuery)
php:
<?php
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
$data = '';
}else{
$data = 'some html';
}
echo $data;
}
Your page is slowing down because you are creating a new interval every time you call the liveCheck function. Over time, you have many intervals running and sending requests to your PHP file concurrently. You can verify this behavior by opening the developer console in your browser and monitoring the Network tab.
What you should do instead is set the interval once, and perform the $.ajax call inside that interval. Additionally, it's good practice to not send a new request if a current request is pending, by implementing a boolean state variable that is true while an request is pending and false when that request completes.
It looks like the intended behavior of your function is to just reload the page when the $online_status->status changes, is that correct? If so, change your PHP to just echo true or 1 (anything really) and rewrite your JS as:
function liveCheck() {
if (liveCheckPending == true)
return;
liveCheckPending = true;
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST'
}).done(function(data){
if (!data.error)
location.reload();
}).always(function(data){
liveCheckPending = false;
});
}
var liveCheckPending = false;
setInterval(liveCheck, 10000);

"Automatically update time in PHP using Ajax - display

I wish to show the current local time on my weather web site.
This is the code that I use from a query :"Automatically update time in PHP using Ajax" posted 2 years ago
<?php
echo "<html>
<head>
<title>Realtime clock</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script src='http://code.jquery.com/jquery.js'></script>
<script>
$(document).ready(function(){
setInterval(_initTimer, 1000);
});
function _initTimer(){
$.ajax({
url: 'timer.php',
success: function(data) {
console.log(data);
data = data.split(':');
$('#hrs').html(data[0]);
$('#mins').html(data[1]);
$('#secs').html(data[2]);
}
});
}
</script>
</head>
<body>
<span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
</body>
</html>"; ?>
<?php date_default_timezone_set("Australia/Brisbane");
echo "Current Time: ". date("H:i:s"). " AEST";
?>
This is what I getwhen I run this:
17:05:10 Current Time: 17:01:30 AEST
What I am aiming to achieve is:
Current Time: 17:05:10 AEST with the time updating every second.
Is there some addition that I need to make in the final echo statement? Or do something else
please help
Thanks
To show current time every second you could use jquery to show time, instead of running ajax on server for every second
Try this:
var nIntervId;
function updateTime() {
nIntervId = setInterval(flashTime, 1000);
}
function pad(n) { return ("0" + n).slice(-2); }
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
function flashTime() {
var now = new Date();
var h = now.getHours().pad(2);
var m = now.getMinutes().pad(2);
var s = now.getSeconds().pad(2);
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time);
}
$(function() {
updateTime();
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="my_box1">
</div>
I assume you have made a separate timer.php file just to echo server time. As your current page is loading just once, the initial server time will not be updated that is your "current time value". Whereas the remaining DOM will be updated with the server time because of ajax code. If you want both times to be same you will have to reload the whole page which is not correct. Hence, I suggest you to display only one time which should be your ajax result.
timer.php:
<?php
date_default_timezone_set("Australia/Brisbane");
echo date("H:i:s");
?>

Pass variable with jquery, open php page and pick it up

I have two pages. On page one, called test1.html, I try to retreive the users timezone. I would like to send it of to a php page called test2.php and load that page instead of test1 with the variable (timezone). This is the code.
Test1.html:
<script type="text/javascript">
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
$.ajax({
type: 'POST',
url: 'test2.php',
data: {'timezone': timezone},
cache: false,
success: function(){
setTimeout(function () {
window.location = 'test2.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
});
});
</script>
Test2.php
<?php
if(isset($_POST['timezone']))
{
$tz = $_POST['timezone'];
echo "Timezone is " .$tz;
}
else {
echo "Fail!";
}
?>
On pageload of test2.php, I only ever get the 'Fail!' message. The jquery and php part do work correct as I tested it with an alert call in test1.html to log the reponse from the php page. It gave the response I expected.
I think I lose my variable when the code is executed to reload test2.php in the same window. I just don't know how to bypass this problem. I want to use POST rather then GET if possible.
Any help greatly appreciated.
Little note: Idealy I want to use this javascript and the php to be on the same page but the 'problem' there is that php is of course executed serverside first and then it runs je js client side afterwards...
An alternative solution that still allows you to use POST, which you said you'd like, is to store the information in a session variable. The session is an object that can be used to store values between requests. See http://php.net/manual/en/book.session.php
Test1.html:
<script type="text/javascript">
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
$.ajax({
type: 'POST',
url: 'test2.php',
data: {'timezone': timezone},
cache: false,
success: function(){
setTimeout(function () {
window.location = 'test3.php';
}, 3000); }
});
});
</script>
Test2.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Store posted timezone in the session, which will be available in future calls
if(isset($_POST['timezone'])) {
$_SESSION['timezone'] = $_POST['timezone'];
}
else {
echo "Fail!";
}
?>
Test3.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_SESSION['timezone']) {
echo "Your timezone is " . $_SESSION['timezone'];
} else {
echo "Fail!";
}
You are misunderstanding the flow of how your client and server are interacting with each other. Your code sends a POST request to test2.php, and THEN (in the success callback that triggers when your request is done) it redirects to test2.php. The first time test2.php is run, it gets the timezone POST variable, but the second time it doesn't. You can see this by looking at network traffic in your browser's developer tools - you'll see two requests to test2.php. The first will return "Timezone is...", and the second (which your browser is showing) says "Fail!"
There are different ways to get what you want, but the easiest would be to skip the AJAX altogether and just send the timezone along with the redirect:
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
// This redirects to test2.php while setting a GET parameter called "timezone"
window.location = 'test2.php?timezone='+encodeURIComponent(timezone);
});
<?php
if(isset($_GET['timezone']))
{
$tz = $_GET['timezone'];
echo "Timezone is " .$tz;
}
else {
echo "Fail!";
}
?>

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

How to access PHP session variables from jQuery function in a .js file?

How to access PHP session variables from jQuery function in a .js file?
In this code, I want to get "value" from a session variable
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.
So in page.php:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
(function ($) {
$.my_progress_bar = function(percent) {
$("#progressbar").progressbar({
value: percent
});
};
})(jQuery);
You can pass you session variables from your php script to JQUERY using JSON such as
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe#jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (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;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file

Categories