Get php mysql result in javascript variable - javascript

I have this code which works very well. But I wanted use mysql.
Here is the code that works:
<?php if (date('w') == 2) { { ?>
<script> $(function() {
var times = [
// mysql import start
{'id': '1', 'name': 'Mardi 5H55', 'end': new Date('2017-01-31 05:55:00'),},
{'id': '2', 'name': 'Mardi 8H40', 'end': new Date('2017-01-31 08:40:00'),},
{'id': '3', 'name': 'Mardi 11H30', 'end': new Date('2017-01-31 11:30:00'),},
{'id': '4', 'name': 'Mardi 14H05', 'end': new Date('2017-01-31 14:05:00'),}
// mysql import end
];
// Initialize the table values
$.each(times, function( key, value ) {
$('#mau-mpl').append('<tr><td>'+value.name+'</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-'+value.id+'-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
});
function countdown()
{
var now = new Date();
console.log('updating time');
$.each(times, function( key, value ) {
var left = value.end - now;
var days = Math.floor( left / (1000 * 60 * 60 * 24) );
var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
var seconds = Math.floor( (left % (1000 * 60)) / 1000 );
displayTime = '';
if (days > 0) {
displayTime = + days + " jr ";
}
if (minutes > 0) {
displayTime = displayTime + hours + " H " + minutes + " Mn " + seconds + " Sec ";
}
echo = "Deja parti";
$('#player-'+value.id+'-expiration').text(displayTime)
});
}
timer = setInterval(countdown, 1000);
});</script><?php } } ?>
As you see my data that I want to put is after mysql import start.
I made a php file that fetches data from mysql and I have this result:
{'id': '1', 'name': 'Mardi 5H', 'end': new Date('2017-01-31 05:00:00'),},
{'id': '2', 'name': 'Mardi 6H', 'end': new Date('2017-01-31 06:00:00'),},
{'id': '3', 'name': 'Mardi 7H', 'end': new Date('2017-01-31 07:00:00'),},
The php file is:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// {'id': '1', 'name': '5H', 'end': new Date('2017-01-31, 05:55:00'),},";
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
} $conn->close();
?>
+---+----------+---------------------+
| 1 | Mardi 5H | 2017-01-31 05:00:00 |
+---+----------+---------------------+
| 2 | Mardi 6H | 2017-01-31 06:00:00 |
+---+----------+---------------------+
| 3 | Mardi 7H | 2017-01-31 07:00:00 |
+---+----------+---------------------+
How do I put the result in javascript variable between "mysql import start" and "mysql import end" ?

You can do this :
var js = <?php echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "')}"; ?>
But warning, I remove bad characters on your object at the last :
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
---------------------------------------------------------------------------------------------------------------------------------^-^^^^^

You can set var with a lot diferent ways ,ajax,embebed javascript code inside php code...
When you want get a PHP object or var to javascript you need serialized the object to JSON in your php code, then you need set your JSON string and convert this string to a valid javascript object.
JSON is a string like this
"{'propertyname':'stringvalue','property2':true,'property3':null,'property':[...]}"
If now you can parse JSON on javascript code block
index.php
<?php
$result = getData() // your data like you want =>[ multiple objects ]
$resultJSON = json_encode($result); // "[{..},{...}]"
?>
<script>
var jsondata = parse.JSON('<?php echo $resultJSON ?>') ;
</script>
But i think is better slice the html/javascript code from php code, and get vars from ajax for example.

You can use AJAX call to a PHP script to store the data into Javascript variables.
In the following file the AJAX call using JQuery is demonstrated to store the data into Javascript
<?php if (date('w') == 2) { { ?>
<script>
$(function() {
var times = $.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
return data;
}
});
$.each(times, function(key, value) {
$('#mau-mpl').append('<tr><td>' + value.name + '</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-' + value.id + '-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
});
function countdown() {
var now = new Date();
console.log('updating time');
$.each(times, function(key, value) {
var left = value.end - now;
var days = Math.floor(left / (1000 * 60 * 60 * 24));
var hours = Math.floor((left % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((left % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((left % (1000 * 60)) / 1000);
displayTime = '';
if (days > 0) {
displayTime = +days + " jr ";
}
if (minutes > 0) {
displayTime = displayTime + hours + " H " + minutes + " Mn " + seconds + " Sec ";
}
echo = "Deja parti";
$('#player-' + value.id + '-expiration').text(displayTime)
});
}
timer = setInterval(countdown, 1000);
});
});</script><?php } } ?>
Following is the code which fetches the data from the database.
Let's call this file api.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//storing result into an array
$array = mysql_fetch_row($result);
}
$conn->close();
//encoding the array into JSON
echo json_encode($array);
?>

Related

javascript checking time and insert data using setInterval

hi guys need help on this one i have a javascript code that identify and display the time on pc(it is base on pc time). i have this condition when it is true should insert the data to database. i use setinterval so when the condition is true it will go to that page or php code(fetch.php code is below). i post all the code in below hopping of help guys. WELL THE PROBLEM IS THAT THE IT IS NOT INSERTING DATA INTO DATABASE.
here is the index.php
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
if(h == '6' && m == '00')
{
$(document).ready(function() {
setInterval(function () {
$('#auto').load('fetch.php')
},1000);
});
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="startTime()">
<div id="txt"></div>
<div id="auto"></div>
</body>
</html>
here is the fetch.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tbl(available)
VALUES ('200')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

How to auto update database mysql using javascript in html

I want to auto update my database when the countdowntimer is == 0 or < 0 without reloading the page. Only a certain block will be reload or reload the script/code. How can i auto update my database in mysql when the distance is < 0? I try the reload(); and .load(location.href("#")); But they reload the page.
I use PHP as my backend
In JAVASCRIPT
<script type="text/javascript">
function createCountDown(elementId, date) {
var countDownDate = new Date(date).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById(elementId).innerHTML = days + 'd ' +
hours + 'h ' +
minutes + 'm ' +
seconds + 's ';
if (distance < 0) {
clearInterval(x);
document.getElementById(elementId).innerHTML = "Expired";
}
}, 1000);
}
You need to use AJAX.
Example:
xhttp.open("POST", "path/to/post/handler.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
In your case:
if (distance < 0) {
clearInterval(x);
document.getElementById(elementId).innerHTML = "Expired";
//this is where you update the database:
xhttp.open("POST", "path/to/post/handler.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//use the xhttp object to send(POST) values to the database.
xhttp.send("message=Expired&id=242");
}
More info Here
What are you using in the back end?
You will need to handle the JavaScript POST:
Example PHP would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $this->mysqli->prepare("UPDATE yourTable SET status=? WHERE id=?");
$stmt->bind_param('si', $_POST['message'], $_POST['id']);
$stmt->execute();
return $stmt->affected_rows;
$conn->close();
?>
Let me know in the comments if it works...

creating custom time algorith like timeago in javascript

I want a custom time algorithm like javascript. I was able to achieve this using php but am not able to do the same with javascript!
WHat i had in php was like.....
PHP FIDDLE(i want something like this in js output)
function getTime($mytime){
// $mytime is a datetime sql database format time
$thetime = strtotime($mytime);
$q = new DateTime($mytime);
$current_time = date('Y-m-d H:i:s',time());
$w = new DateTime($current_time);
$result = $w ->diff($q);
$string = "";
$year = $result->y;
$month = $result->m;
$day = $result->d;
$hour = $result->h;
$min = $result->i;
$sec = $result->s;
if($year==0){
if($month==0){
if($day==0){
if($hour==0){
if($min==0){
if($sec <30){
$string .= "Just now";}else if($sec<60){ $string .= "A few seconds ago";}
}else{
if($min<5){$string .="A few minutes ago";}else if($min>=5){$string .=$min . ' minutes ago'; }
}}else{
if($hour<6){$string .=$hour . ' hours ago';}else if($hour>=6){
$chour = (date('H',$thetime));
if( ($chour>=5)&&($chour<=17) ){$string .= 'Today at ' .date('h.m a',$thetime);}else{$string .= 'Tonight at '. date('h.m a',$thetime);}}
}}else{
if($day==1){$string .= "Yesterday at " . date('h:m a',$thetime);}else if(($day>1) && ($day<=7)){$string .= $day . " days ago";}else if($day>7){$string .= date('M, d',$thetime) . ' at '. date('h:i a',$thetime);}
}}else{
if($month<5){$string .=$month . ' months ago'; }else if($month>=5){$string .= date('M,d',$thetime) .' at ' . date('h.i a',$thetime) ;}
}}else{
$string .=date('dS M , Y',$thetime) .' at '. date('h.i a',$thetime);
}
return $string;
}
What i thought was to dynamically update time using javascript! so i did this......
$(function(){
var $second = 1000;
var $minute = $second * 60;
var $hour = $minute * 60;
var $day = $hour * 24;
setInterval(function(){
$('.comment').each(function(){
var $this = $(this);
var $time = new Date($this.attr('datetime'));
var $now = new Date();
var $distance = $now - $time;
var $days = Math.floor($distance / $day);
var $hours = Math.floor(($distance % $day) / $hour);
var $minutes = Math.floor(($distance % $hour) / $minute);
var $seconds = Math.floor(($distance % $minute) / $second);
var $time_string = '';
if($days > 0) {
$time_string = $time_string + $days + ' Day(s) ';
}
if($hours > 0) {
$time_string = $time_string + $hours + ' Hour(s) ';
}
if($minutes > 0) {
$time_string = $time_string + $minutes + ' Minute(s) ';
}
if($seconds > 0) {
$time_string = $time_string + $seconds + ' Second(s)';
}
$this.text($time_string);
});
}, 1000);
});
but his outputs something like this fiddle here.
What i wanted is like my prev. php output i.e X min ago or X seconds ago or 12 May 2014 etc how do i implement my above php code with this js ?

Javascript countdown just working on Chrome

Well, I'm making a game, and in my game I have a countdown script in javascript that receives the date when the building upgrade is over, and makes a countdown, and when the countdown ends, executes a script that upgrades the building to the next level.
But just works in google chrome, and in the other browsers appears like that:
Firefox:
Google Chrome
Just the Javascript:
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
Complete function:
function factory_update($get){
$userid = $_SESSION['userid'];
$query00 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result00 = mysql_query($query00) or die(mysql_error());
while($row00 = mysql_fetch_array($result00)){
$factory_upgrade = $row00['userid'];
}
if(!isset($factory_upgrade)){
echo "Sem melhoramentos.";
return 0;
}
$query01 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result01 = mysql_query($query01) or die(mysql_error());
while($row01 = mysql_fetch_array($result01)){
$factory_level = $row01['new_level'];
$factory_date = $row01['upgraded'];
}
if ($get == "load")
{
echo '<div class="message_upgrades" ">';
echo '<div class="loading"><img src="/images/loading.gif"></img></div>';
echo '</div>';}
else
{
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
echo '<div class="success_upgrades">';
echo '<div class="upgrade_text"><b>Nivel: </b>' . $factory_level . '</div><div class="div_separator"></div><div class="upgrade_text"><b>Duração:</b>
<div class="secsBox" id="secsBox"></div>
<script type="text/javascript">cdtd();</script></div><div class="div_separator"></div>
';
echo '<div id="close" class="stop_upgrade" ></img></div>';
echo '</div>';
echo '<script>
$(".stop_upgrade").click(function (e) {
e.preventDefault();
$(factory_upgrade2).empty();
setTimeout(function(){
$("#factory_upgrade2").load("/include/upgrade_cancel.php");
$("#factory_upgrade").load("/include/factory_update.php");
$("#load").load("/include/cabecalho_content.php");
$("#industrial").fadeIn();
$(loader1).delay(1000).hide(0);
}, 100);
});
</script>
';
}
}
The format of $factory_date is invalid according to standard JavaScript and Chrome happens to be able to parse it.
For better results, stick to these Date constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month [, day, hour, minute, second, millisecond]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Javascript/PHP countdown timer stops at a certain time?

I have this code for a countdown timer. its basically a combination of PHP/Javascript countdown timer which will gets the $end_date from a Mysql table/field.
The problem is that it will stop automatically (which is unwanted) at a certain time.
For example: I set the $end_date to September 19 2013 11:30:00 AM GMT in mysql database.
the countdown starts and works fine and starts counting down as it should. However, when the countdown timer reaches September 19 2013 13:00:00 PM GMT it will stop and it will show the Times Up message! Basically it will stop working or counting down once the $end_date has been changed to 13:00:00 PM.
I cannot see anything in my code that will cause this issue. apart from this line:
if ($now < $exp_date ) {
?>
but again, this line only tells the script when to start counting and as far i can see it shouldn't stop the countdown timer to stop as long as the timer has not reached the $end_date. or am I missing something?
here is my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s A T", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
any help would be greatly appreciated.
13:00:00 PM is not a valid time. AM and PM are used to indicate which side of the 12-hour cycle the time is. You cannot logically say you're on the 13th hour of the 12 hour side of the clock.
EDIT: For clarity: 13:00 == 1 PM, 13:00 PM == nothing.

Categories