how can print data from database in javascript - javascript

i want to print date column from database in javascript code
this is the original javascript code i want to change date countdown
<script type="text/javascript">
$(document).ready(function() {
$('#countdown').countdown('2017/07/10 06:32:11', function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});
});
</script>
and this code after edit :
<?php
$count = $DB_con->prepare("SELECT * FROM `auction` WHER ORDER BY id DESC");
$count->execute();
foreach ($count->fetchAll() as $rowL)
{
?>
<script type="text/javascript">
$(document).ready(function() {
var countdw;
countdw = = <?php echo $rowL['dateauction']; ?>
$('#countdown').countdown(document.write(countdw), function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});
});
</script>
<?php
}
?>

If you only have one value from the database, you don't need to loop anything, although I can't imagine you have one whole table dedicated to one row unless you have a bunch of rows chronicled, in which case you probably should limit to one row to return. At any rate, it's likely it should look something more like this:
<?php
# You probably just need to limit 1 and only select the column you need
$query = $DB_con->prepare("SELECT `dateauction` FROM `auction` ORDER BY id DESC LIMIT 1");
$query->execute();
# Just fetch without a loop
$row = $query->fetch(PDO::FETCH_ASSOC);
?>
<script type="text/javascript">
$(document).ready(function() {
// You should probably have quotes and a semicolon, also only one equal sign
var countdw = '<?php echo $row['dateauction'] ?>';
$('#countdown').countdown(document.write(countdw), function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});
});
</script>

Related

How can I trigger PHP if a MySQL gets a new highest ID?

Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");

jQuery setInterval update PDO content

I'm wanting to run a jquery script that updates a content box every so often. I want the contents on this box to be from my database.
So far I have this, which isn't much, but not sure how the best way would be to replace the content. This is how my approach would be, but i'm sure its incorrect and there is a better way, also this does not work anyways.
<div id="list"> List here </div>
<script>
$(document).ready(function() {
setInterval(function(){ updateList(); }, 8000);
});
function updateList(){
$('#list').html(
<?php
$sql = "SELECT * FROM list WHERE enable = 1 ORDER BY id DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$u = $stm->fetchAll();
foreach ($u as $list) {
?>
"<?php echo $list['name']; ?>";
<?php
} ?>
);
}
</script>
My question is, how would I be able to do this? Thanks
You need to execute an Ajax function that call PHP server side operations like this (with <ul><li> list to show all elements separeted, but optional) :
list.php
<?php
function get_list() {
$sql = "SELECT * FROM list WHERE enable = 1 ORDER BY id DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
if($_GET['update']) {
$html = '<ul>';
foreach(get_list() as $element) {
$html. = '<li>'.$element['name'].'</li>';
}
echo $html . '</ul>';
die();
}
?><html>
<head>
<title>...</title>
Some css and js...
</head>
<body>
<div id="list">
</div>
<script>
$(document).ready(function() {
setInterval(function(){
$.get('list.php?update=1', function(data) {
$('#list').html(data);
});
}, 8000);
});
</script>
</body>
</html>
As stated in my comment :
PHP is just a preprocessor
Therefore I recommend the use of AJAX and a separated PHP script to do the job (and an <ul>):
getEnabledsNames.php
<?php
$sql = "SELECT * FROM list WHERE enable = 1 ORDER BY id DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$u = $stm->fetchAll();
$u = array_map(function($elem){
return $elem['name'];
}, $u);
header('Content-Type: application/json');
echo json_encode($u);
?>
The JS code
let interval;
$(document).ready(()=>{
interval = setInterval(updateFromDb, 8000);
});
function updateFromDb(){
$.get(
"getEnabledsNames.php",
(data)=>{
$("#list > ul").html("");
data.forEach(e=>{
$("#list > ul").append(`<li>${e}</li>`);
});
}
).fail(/* function to handle failure here */);
}
The HTML
<div id="list">
<ul></ul>
</div>
Try This
var gtimer;
$(document).ready(function() {
clearInterval(gtimer);
gtimer = window.setInterval(function() {
clearInterval(gtimer);
updateList();
},8000);
});

AJAX get() data

I have a block of jQuery which uses the $.get() method in a setInterval(). I don't understand how to get data from the second URL to the jQuery code.
Jquery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.getJSON("check_time.php", function(update) {
if (update) {
$("#slideshow").load("phppage.php");
}
});
}, 600000);
</script>
PHP - check_time.php
<?php
require_once('connect_pdo.php');
header('Content-type: application/json');
$stmt = $conn->prepare("$sqlst = $conn->prepare("SELECT COUNT(*) AS count
FROM ads
WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$sqlst->execute();
$row = $sqlst->fetch();");
$stmt ->execute();
$row = $stmt ->fetch();
$update = $row['count'] > 0;
$updtstatus = json_encode($update);
echo "$updtstatus";
?>
I am not getting the variable from check_time.php to the update variable in function(update).
Small alter in php page
$updtstatus = json_encode(array('count'=>$update));
echo $updtstatus;
Now your JSON is in fact something like this {"count":"true"}.
So change your if statement slightly.
$.getJSON("check_time.php", function(update) {
if (update.count===true) {
$("#slideshow").load("phppage.php");
} else {
console.log("No results");
}
});
This fiddle simulates the above answer
Your jQuery functions expects data to be returned in JSON format, so simply do so :) I've also found some flaws within your PHP code. This should do the trick:
$.get('check_time.php', function(data) {
console.log(data); // Console logging is always good
if (data.status) {
alert('Load slideshow');
}
});
check_time.php
<?php
require_once('connect_pdo.php');
$json = []; // The JSON array which will be returned
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM ads WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$stmt->execute();
$json['status'] = (bool) $stmt->rowCount(); // Status is either false (0) or true (> 0)
echo json_encode($json);

PHP json_encode displaying null

I am running an SQL Query in PHP and putting the values into a JS variable:
<?php
$return_arr = array();
$sql="SELECT * from customer_billing group by productname ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs)) {
$return_arr[] = $result["productname"];
}
echo json_encode($return_arr);
?>
<script type="text/javascript">
$(function() {
var availableTags = <?php echo json_encode($return_arr); ?>
//autocomplete
$(".auto").autocomplete({
source: availableTags
});
});
</script>
I have 3 rows with the column productname equal to:
Integra Fibre Unlimited
Integra Fibre Unlimited (RRP: £59.95)
Integra Professional Web Hosting
and when i use echo json_encode($return_arr);, it displays like:
"Integra Fibre Unlimited",null,"Integra Professional Web Hosting"
it just doesn't like displaying the second one
Try:
// some code
while($result=mysql_fetch_array($rs)) {
$return_arr[] = utf8_encode($result["productname"]);
}
echo utf8_decode(json_encode($response));

Opencart successful order ID and Total from JavaScript

I need to run JavaScript on the successful order's page and get two things: order ID and total order amount. The code looks like:
<script type="text/javascript">
// Some code here
arr.push([
"create_order",
{order_id: "*order_id*", sum: *sum*}
]);
</script>
Questions
Where should I paste my script? If into success.tpl than where exactly? If into header.tpl than how to run it only on the page of successful order?
Which variables I should to use? I have tried this, it did not work:
{order_id: "<?php echo $order_id; ?>", sum: <?php echo $product_total; ?>}
P. S. Opencart version is 1.5.6
The problem here is that on success page all the order data is already unset (deleted) from session variables. That's why your code cannot succeed.
Look into catalog/controller/checkout/success.php and change the beginning of the index() function to this:
public function index() {
$this->data['order_id'] = 0; // <-- NEW LINE
$this->data['total'] = 0; // <-- NEW LINE
if (isset($this->session->data['order_id'])) {
$this->data['order_id'] = $this->session->data['order_id']; // <-- NEW LINE
$this->data['total'] = $this->cart->getTotal(); // <-- NEW LINE
$this->cart->clear();
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
}
$this->language->load('checkout/success');
Now you have the order_id and cart's total values stored in template variables, so just use them in your success.tpl (not header):
<?php if($order_id) { ?>
<script type="text/javascript">
// Some code here
arr.push([
"create_order",
{order_id: '<?php echo $order_id; ?>', sum: '<?php echo $total; ?>'}
]);
</script>
<?php } ?>
This should be enough.
The previous answer needs to be updated for later versions of Opencart
for 2.2.0 it is
$data['order_id'] = 0;
$data['total'] = 0;
and
$data['order_id'] = $this->session->data['order_id'];
$data['total'] = $this->cart->getTotal();
instead of the new lines indicated previously

Categories

Resources