window.location.reload(true); doesn't work together with database question - javascript

I have a countdown script that takes the countdown date from a database. When the countdown is finished the page should reload and then get a new date from the database and then start a new counter. All is working as it should, but after the reload it seems that it doesn't get the time to ask the new question from the database. So the counter just sits at zero on the expired date. I've tried so many different ways to reload the page and none are working.
<?php
include '../includes/db.php';
$sql = $conn->query("SELECT gamedate FROM games WHERE gamedate > NOW() ORDER BY gamedate LIMIT 0 , 1 ") or die($conn->error());
while ($row = mysqli_fetch_array($sql))
{
$gamedate = $row['gamedate'];
}
?>
<div class="game" data-date="<? echo $gamedate; ?>" id="Countdown"></div>
<script>
$(".game").TimeCircles({count_past_zero: false},).addListener(countdownComplete);
function countdownComplete(unit, value, total){
if(total <= 0){
window.location.reload(true);
}
}
</script>

Related

SQL table update frequency in Seconds with AJAX

I have a form where different users can update data. I have implemented a write protection script with AJAX to avoid conflicts if more then one user is working in the form. As i do not know it better ;) i have solved this in that way:
If the user open form the related user_id and timestamp will be updated in my SQL table for the specific form ID. With AJAX i check every 3 seconds if this user is still on the form and do a update of the timestamp. If another user is opening the form in parallel, i check if this timestamp is older then 10 seconds. If this is true i update the SQL table with the new user_id and timestamp every 3 seconds. If the timestamp from the first user is not older then 10 seconds i just lock the form by adding a overlay with a high z-index. So the user can see the infomation but can not change it. I also show a information that this form is currently locked.
This sounds simple and is working ... more or less...
Here comes my problem:
It seems like that due to for me some unknown reason the SQL table does not gets updated every 3 seconds. (Edit:) I is working correctly sometimes for a longer time. But sometimes but not very often the SQL update is not initiated within 9 seconds (this is 3 tries). I added my script bellow, may be my routine is not optimal for my needs? Would be happy if you can help me to optimize it to avoid those update delays (hicks).
I am working local. Using the XAMPP Control Panel v3.2.4. PHP Version 7.4.6
Code in my frontend page:
<script type="text/javascript">
var auto_refresh = setInterval(
function() {
$('#login')
.load('ajax-audit_execute_login.php?audit_id=<?= $audit_id ?>&user_id=<?= $user['id'] ?>');
}, 3000); // refresh every 3000 milliseconds
</script>
<div id="login">
<?php
// Check if someone is logged in into that form
$statement = $pdo->prepare("SELECT login_at, login_by FROM audit WHERE id = :id");
$result = $statement->execute(array(':id' => $audit_id));
$login = $statement->fetch();
// Calculate the tim ebetween the now and the latest login timestamp
$ts2 = strtotime(date("Y-m-d H:i:s"));
$ts1 = strtotime($login['login_at']);
$seconds_diff = $ts2 - $ts1;
// If its the same user who locked the form latest do just an update of the timestamp
if ($login['login_by'] == $user['id']) {
$query = "UPDATE audit
SET login_at = :login_at,
login_by = :login_by
WHERE id = :audit_id";
$pdoResult = $pdo->prepare($query);
$pdoExec = $pdoResult->execute(array(":login_at" => date("Y-m-d H:i:s"), ':audit_id' => $audit_id, ':login_by' => $user['id']));
$locked = 0; // Form is not locked
} else {
// If its another user check if the timestamp is older then 10 seconds
if ($seconds_diff > 10) {
// The timestamp is older then 10 seconds. Update the SQL data for new user.
$query = "UPDATE audit
SET login_at = :login_at,
login_by = :login_by
WHERE id = :audit_id";
$pdoResult = $pdo->prepare($query);
$pdoExec = $pdoResult->execute(array(":login_at" => date("Y-m-d H:i:s"), ':audit_id' => $audit_id, ':login_by' => $user['id']));
$locked = 0; // Form is unlocked for the new user
} else {
// Timestamp is not older so the form is locked
$statement = $pdo->prepare("SELECT users.vorname, users.nachname, companies.company_name
FROM users
JOIN companies ON users.cid = companies.cid
WHERE users.id = :id");
$result = $statement->execute(array(':id' => $login['login_by']));
$locked_by = $statement->fetch();
$locked = 1; // Form is locked
}
}
?>
<?php if ($locked == 1) { ?>
<style>
div.fadeMe {
opacity: 0.1;
background: #000;
width: 100%;
height: 100%;
z-index: 100;
top: 0;
left: 0;
position: fixed;
}
</style>
<?php
// If the form is locked adding a transparent overlay to avoid changes on the form.
// Add a alert and inform the user about the situation.
?>
<div class="fadeMe"></div>
<div class="alert alert-danger mt-0 mb-0 rounded-0" role="alert">
<p class="mb-0 text-center">
<i class="fa-solid fa-lock mr-1"></i>
Die Bearbeitung dieses Fragebogens ist durch <?=$locked_by['vorname']?> <?=$locked_by['nachname']?> [<?=$locked_by['company_name']?>] gesperrt. </p>
</div>
<?php } else { ?>
<?php } ?>
</div>
My code in the AJAX file in "background":
Which is more or less the same as in the front end.
<?php
$audit_id = $_GET['audit_id'];
$user_id = $_GET['user_id'];
?>
<div id="login">
<?php
// Check if someone is logged in into that form
$statement = $pdo->prepare("SELECT login_at, login_by FROM audit WHERE id = :id");
$result = $statement->execute(array(':id' => $audit_id));
$login = $statement->fetch();
// Calculate the tim ebetween the now and the latest login timestamp
$ts2 = strtotime(date("Y-m-d H:i:s"));
$ts1 = strtotime($login['login_at']);
$seconds_diff = $ts2 - $ts1;
// If its the same user who locked the form latest do just an update of the timestamp
if ($login['login_by'] == $user_id) {
$query = "UPDATE audit
SET login_at = :login_at,
login_by = :login_by
WHERE id = :audit_id";
$pdoResult = $pdo->prepare($query);
$pdoExec = $pdoResult->execute(array(":login_at" => date("Y-m-d H:i:s"), ':audit_id' => $audit_id, ':login_by' => $user_id));
$locked = 0; // Form is not locked
} else {
// If its another user check if the timestamp is older then 10 seconds
if ($seconds_diff > 10) {
// The timestamp is older then 10 seconds. Update the SQL data for new user.
$query = "UPDATE audit
SET login_at = :login_at,
login_by = :login_by
WHERE id = :audit_id";
$pdoResult = $pdo->prepare($query);
$pdoExec = $pdoResult->execute(array(":login_at" => date("Y-m-d H:i:s"), ':audit_id' => $audit_id, ':login_by' => $user_id));
$locked = 0; // Form is unlocked for the new user
} else {
// Timestamp is not older so the form is locked
$statement = $pdo->prepare("SELECT users.vorname, users.nachname, companies.company_name
FROM users
JOIN companies ON users.cid = companies.cid
WHERE users.id = :id");
$result = $statement->execute(array(':id' => $login['login_by']));
$locked_by = $statement->fetch();
$locked = 1; // Form is locked
}
}
?>
<?php if ($locked == 1) { ?>
<style>
div.fadeMe {
opacity: 0.1;
background: #000;
width: 100%;
height: 100%;
z-index: 100;
top: 0;
left: 0;
position: fixed;
}
</style>
<?php
// If the form is locked adding a transparent overlay to avoid changes on the form.
// Add a alert and inform the user about the situation.
?>
<div class="fadeMe"></div>
<div class="alert alert-danger mt-0 mb-0 rounded-0" role="alert">
<p class="mb-0 text-center">
<i class="fa-solid fa-lock mr-1"></i>
<?php
// just for development purpose only to see the reaction time on the SQL update
// See every 3 seconds the updated time stamp and the calculated time difference in sseconds.
echo $login['login_at'];
echo " ";
echo $seconds_diff
?>
Die Bearbeitung dieses Fragebogens ist durch <?=$locked_by['vorname']?> <?=$locked_by['nachname']?> [<?=$locked_by['company_name']?>] gesperrt. </p>
</div>
<?php } else { ?>
<?php } ?>
</div>
Ok so there's a looooooot of issues here.
If you're gunna do any sort of ongoing validation, you don't return the entire HTML body every request, you return a small JSON reply and use that to control the HTML via JS. Generally it's a good practice to separate your HTML \ JS from your API \ validation layer altogether.
You shouldn't be managing data locks on the front end at all. Trusting the client to maintain data integrity is a big no-no in general. It seems like this should be handled as some sort of batched queue. You should never "recreate that effect" via locking and unlocking forms client side.
Your "silent" form key (or any validation stuff) should be handled via sessions or OAUTH, not GET params.
That said the issue is most likely a result of a race condition cause by table locking. If 2 users are both trying to lock \ access records which have a gap overlap user 2 has to wait until user 1's lock releases on that range.
This in turn makes the PHP "silently" block requests while they wait on the table locks to release. If you didn't properly index your user \ timestamp columns with the above queries, it could put a lock on all the other users update queries while it waits depending on how you set up your indexes... Which can then lead to your timer creating callback hell since every user is running it the whole time their logged in.
You should log your DB response time specifically to pin down if this is an issue, but regardless there's some architectural issues that should be addressed regardless.

update database table on session timeout in php

I have a php code as shown below in which session timeout happen after 60 mins when there is no activity. The following code is inside the file /mno.php. My login and logout code is also in the same file /mno.php.
/mno.php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
header('location: /mmo.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
The table trace_users in the code keeps the track of all logged in users. In that table, there are two columns user_name and open. The value is set to true/false when any user log in/log out.
I have included sql query in which I am trying to update a table when there is no activity but unfortunately the column value is not getting set to false for that particular user when no activity happens for 60 mins.
This is what I have tried:
After doing some research, I think I have to run a timer (js/ajax). In the javascript shown below I have calculated the difference between the Last Activity and the Current time.
If its more than 60 mins, then it will update a db table. This is what I have tried but I believe more need to be done in order to update a table in db.
<script>
let x = setInterval(function() {
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>
let now = <?php echo time() ?>;
let difference = now - lastActivity;
if (difference > 3600) {
clearInterval(x);
}
}, 1000
);
</script>
Problem Statement:
I am wondering what changes I should make in the js (or php) code above so that when there is no activity for 60 mins, it should update the column open to false (in the table trace_users) for that particular user.
Edit 1:
My login code and session history code is in the same file /mno.php. I have placed everything in the same file /mno.php.
I think Vineys and jo0gbe4bstjbs answer is wrong because of when user close browser until 5 seconds, it can't update table after 60 mins and session too. Session deletes just after time in where set in php.ini configuration file.
And Do you mind requesting every 5 seconds is it good way to solve this? It is worst for performance.
If you want solve this problem with professionalism, you should add "last_request" column and delete "open" column from the table and after every request you should update last_requests value to current unix timestamp. And where getting users you should write:
$time = time() - 3600;
"SELECT * FROM `users` WHERE last_request > $time" //active users
"SELECT * FROM `users` WHERE last_request <= $time" //inactive users
And instead of ajax request every 5 seconds you should write setTimeout with 3600 second delay time which run window.location.href= '/mmo.php'; code.
Its way good if you want best performance and exactly result with 60 minute logout
I suppose you realize that this code
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
//...
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
runs on every request and only when a request arrives
Imagine I visit your website and then go out shopping keeping the browser open. What do you think will happen?
NOTHING - because there will be no new request sent to you (assuming you haven't implemented any periodic ajax polling / Websocket mechanism)
So the server won't bother about me until I come back from shopping and refresh the page, only then would the server realize "Hmmm..This guy's LAST_ACTIVITY is older than an hour let me update my trace_users table and set open as false for him"
Coming to your proposed solution, it looks good and avoids the complications of websockets/periodic ajax requests
Just need some minor corrections, follow here for a basic demo
<script>
var lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
var now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server
// but later on it will be incremented by javascript to act as counter
var logoutAfter = 5; //I set 5 sec for demo purposes
var timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
}
}, 1000);
</script>
Here the lastActivity will hold the timestamp when the page was sent by server to browser it will be never changed by scripts on the browser,
now is your counter that you will use to track how much time passed since page was loaded on the browser, you'll increment it every second and check if a given amount of time has been crossed
If true do a ajax request (or simply redirect to logout.php) where you would destroy session and update the trace_users table to mark the user as closed
UPDATE
So ajax will be like
$.ajax({
url: "/close.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
window.location.href= '/mmo.php';
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
and
close.php
<?php
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
// I'm not sure whether the below if condition check is required here or not
// because we have already checked (whether to timeout or not ) in our javascript
// and we call close.php only when it's affirmative
// I encourage you to test and find out :)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Page.php
<!-- CODE TO INCLUDE IN HEADER.PHP -->
<?php
session_start();
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
<!-- CLOSE -->
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
let now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server+
// but later on it will be incremented by javascript to act as counter
let logoutAfter = 5; //I set 5 secs for demo purposes
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/mmo.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("I am inside error");
alert(textStatus);
}
});
}
}, 1000); //<-- you can increse it( till <= logoutAfter ) for better performance as suggested by #"Space Coding"
</script>
</html>
mmo.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name'])?$_SESSION['user_name']:'';
$stmt->bind_param('ss', $open, $usname );
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
This is a simple time validation for web page:
$modified_on = isset($SERVER['HTTP_IF_MODIFIED_SINCE']) ? $SERVER['HTTP_IF_MODIFIED_SINCE'] : null;
$current_time = time();
if (!is_null($modified_on) && ($current_time - strtotime($modified_on)) > 3600) {
session_destroy();
...
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $current_time).' GMT');
...

Show preloader once per visit

I have been trying to figure this out, I want to show preloader only once per visit. How can I do that?
Current code:
$(window).on('load', function() {
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
$('body').delay(350).css({'overflow':'visible'});
})
Could you try the sessionStorage
if ( ! sessionStorage.getItem( 'doNotShow' ) ) {
sessionStorage.setItem( 'doNotShow', true );
$('#preloader').delay(350).fadeOut('slow');
} else {
$('#preloader').hide();
}
Or take a look on this link How to show website preloader only once
No cookie whether session or persistent will provide a reliable solution to this problem. The only way I can see doing this properly would be to record the ip address of the visitor and check to see if that record matches one in a table:
If it doesn't, load the preloader.
If it does, don't load the preloader.
The only possible problem to this is people periodically clear the temp website data they collect so I would implement a timed record system and set it to a reasonable value like 30 days so if they haven't visited your site in 30 days we will presume they have cleared their cache and they will get the preloader, that would change the criteria to;
If visitor is new, load preloader
If visitor is old but less than 30 days, don't load preloader
If visitor is old and more than 30 days, delete record, create new record, load
preloader
Code example below;
#1: Detect IP
<?php
function myIp() {
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$my_ip = myIp();
global $my_ip;
?>
#2: Operations
<?php
// Set preloader status
$play_preloader = "no";
// Check visitor ip records for current ip
$preloader_one = "select ip from preloader where ip='$my_ip'";
$connect_preloader_one = mysqli_query($con, $preloader_one);
$rows_preloader_one = mysqli_num_rows($connect_preloader_one);
// If no record exists, create a new one
if ($rows_preloader_one == 0) {
$preloader_insert = mysqli_prepare($con, "insert into preloader (ip) values (?)");
mysqli_stmt_bind_param($preloader_insert, "s", $my_ip);
mysqli_stmt_execute($preloader_insert);
$play_preloader = "yes";
// If records exist, find records older than 30 days
} else {
$preloader_two = "select ip,date from preloader where ip='$my_ip' and date < DATE_SUB(now(), INTERVAL 30 DAY)";
$connect_preloader_two = mysqli_query($con, $preloader_two);
// If records older than 30 days found
$rows_preloader_two = mysqli_num_rows($connect_preloader_two);
if ($rows_preloader_two > 0) {
// Delete old records
$preloader_delete = "delete from preloader where ip='$my_ip' and date < DATE_SUB(now(), INTERVAL 30 DAY)";
$preloader_delete_query = mysqli_query($con, $preloader_delete);
// Add new record
$preloader_insert = mysqli_prepare($con, "insert into preloader (ip) values (?)");
mysqli_stmt_bind_param($preloader_insert, "s", $my_ip);
mysqli_stmt_execute($preloader_insert);
$play_preloader = "yes";
// If records exist but no records are older than 1 month
} else {
$play_preloader = "no";
}
}
// Preloader
if ($play_preloader == "yes") {
$preloader = "
enter you html/js/css code for the preloader here
";
} else {
$preloader = "";
}
?>
Now save all the above code in a php file then reference it in your html and then call $preloader;
<html>
<head>
<?php include_once ('mypreloader.php'); ?>
</head>
<body>
<?php echo $preloader; ?>
</body>
</html>
This code has been tested on a running server and is working.

Refresh content/page on the hour every hour

I have a code that is meant to refresh the page on the hour, every hour but it doesn't seem to execute...
This is the code:
<?php
date_default_timezone_set('Australia/Sydney');
$date = date("i:s");
list($cur_min, $cur_sec) = explode(':', $date);
$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;
$time=($mins_left*60+$secs_left)*1000;
?>
<script type="text/javascript">
setInterval("refresh()",<?php echo $time; ?>);
function refresh(){
window.location = location.href;
}
</script>
I need it to run off the server clock too and not from when the user lands on the page.
Idealy, would be awesome if it could just refresh the content of every div labeled with the class named "locality"...
I would use DateTime in PHP and for easy convertion use timestamps.
$date = new \DateTime(strtotime(time()), new \DateTimeZone("Australia/Sydney")));
$date->add(new \DateInterval('PT1H'));
$time = $date->format('U') % 3600;
And for JS:
var time = (Math.round((new Date()).getTime() / 1000) % 3600);
if(time > <?= $time ?>){
var rtime = time - <?= $time ?>;
} else {
var rtime = <?= $time ?> - time;
}
setInterval(function(){
window.location.reload(1);
},rtime * 1000);
But im not sure why:
<meta http-equiv="refresh" content="3600">
Will not suffice as it will just refresh an hour later (and so on) of when the user enters the page, doesn't really matter what timezone.
Try this code for the JavaScript part:
function refresh(){
window.location.reload();
}
setTimeout(refresh, <?php echo $time; ?>);
I'm not sure if it will solve your problem, but I tried a few changes:
window.location.reload() is more explicit than window.location = location.href (which, by the way, could be simplified to window.location = window.location)
setTimeout instead of setInterval because if the refreshing fails again for some reason, you don't want to try refreshing again in
put the setTimeout call after the definition of the function to be sure that there isn't a problem with the function not being defined yet
Try it. If that code still doesn't work for you, try looking at your generated HTML and seeing what value for $time was printed. Also check the browser console for any errors.
By the way, the code would be clearer if you renamed the variable $time to $ms_until_start_of_hour.

PHP variable to be used in Javascript code for a game

<script>
$(document).ready(function(){
var oMain = new CMain({
win_occurrence:30, //WIN PERCENTAGE.SET A VALUE FROM 0 TO 100.
slot_cash: 2000000, //THIS IS THE CURRENT SLOT CASH AMOUNT. THE GAME CHECKS IF THERE IS AVAILABLE CASH FOR WINNINGS. THIS SHOULD BE BALANCE OF MY OVERALL BTC ACCOUNT.
min_reel_loop:2, //NUMBER OF REEL LOOPS BEFORE SLOT STOPS
reel_delay: 6, //NUMBER OF FRAMES TO DELAY THE REELS THAT START AFTER THE FIRST ONE
time_show_win:2000, //DURATION IN MILLISECONDS OF THE WINNING COMBO SHOWING
time_show_all_wins: 2000, //DURATION IN MILLISECONDS OF ALL WINNING COMBO
money:<?php include 'getbtcbalance.php'; echo $btcbalance;?> , //STARING CREDIT FOR THE USER - THIS IS GOING TO BE AN ECHO OF USER ADDRESS BALANCE.. So 'getbalance of addressofsessionidvariable'
ad_show_counter:3
(after this isnt necessary to see as works fine)
As you can see, I am trying to get the 'money:' part to be a php variable called $btcbalance from the file getbtcbalance.php.
The php variable $btcbalance works fine on getbtcbalance.php and can be echoed to display the correct balance, I just need to make it work in the js script.
What I did above doesnt work, I just left it there so you can see what I'm trying to do.
Hope someone can help.
EDIT:
Attached as requested is the content of getbtcbalance.php:
<?php
// Getting BTC address from database by using a post function 'selecting row of session username'
//Set btc address as a ssession variable so that it can be used for topup
include_once 'blockconfig.php';
session_start();
$connect=mysqli_connect('localhost', 'root', 'PASSWORD') or die(mysqli_error());
mysqli_select_db($connect, 'test6') or die("Cannot select database");
$sessionusername = $_SESSION['username'];
$res2 = mysqli_query($connect, "SELECT * FROM test WHERE username='$sessionusername'");
if (!$res2) {
printf("Error: %s\n", mysqli_error($connect));
exit();
}
$row=mysqli_fetch_array($res2);
$bitty = $row['btcaddress'];
$_SESSION['btcaddress'] = $bitty;
$btcbalancedetails = $block_io->get_address_balance($bitty);
$btcbalance = "".$btcbalancedetails->data->available_balance."";
// Do below if you need to echo the address on this page, or you can copy / paste it onto another page to echo the btc address
// if (isset($bitty)){
// echo $sessionusername."'s BTC address for TOP-UP: ".$bitty;}
// else {
// echo mysqli_error($connect);
// }
?>
You can include php file before html code then you use php file variable(s).
<?php include 'getbtcbalance.php';?>
<script>
$(document).ready(function(){
var oMain = new CMain({
win_occurrence:30, //WIN PERCENTAGE.SET A VALUE FROM 0 TO 100.
slot_cash: 2000000, //THIS IS THE CURRENT SLOT CASH AMOUNT. THE GAME CHECKS IF THERE IS AVAILABLE CASH FOR WINNINGS. THIS SHOULD BE BALANCE OF MY OVERALL BTC ACCOUNT.
min_reel_loop:2, //NUMBER OF REEL LOOPS BEFORE SLOT STOPS
reel_delay: 6, //NUMBER OF FRAMES TO DELAY THE REELS THAT START AFTER THE FIRST ONE
time_show_win:2000, //DURATION IN MILLISECONDS OF THE WINNING COMBO SHOWING
time_show_all_wins: 2000, //DURATION IN MILLISECONDS OF ALL WINNING COMBO
money:<?php echo $btcbalance;?> , //STARING CREDIT FOR THE USER - THIS IS GOING TO BE AN ECHO OF USER ADDRESS BALANCE.. So 'getbalance of addressofsessionidvariable'
ad_show_counter:3
you are echoing the balance at the time of page load, are you sure it will be same after your page loaded.
it's the constant value then try this-
money:'<?php echo $btcbalance;?>'

Categories

Resources