The below script is for displaying countdown timing
Used code is here with a combination of php,javascript
Tried many ways but no use
<script>
function countdown(endT,callback,val) {
var val,days,hours,minutes,sec,timer;
end = new Date(endT);
end = end.getTime(); //Get initial Date in Milliseconds,
if (isNaN(end)) {
alert('# countdown.js # "Invalid Date", valid format- mm/dd/yyyy hh:mm:ss TT ');
return;
}
timer = setInterval(calculate,1000);//Timer to calculate remaining time
function calculate(){
var current = new Date();
var remaining = parseInt((end - current.getTime())/1000);//remaining seconds,
if (remaining <= 0){
clearInterval(timer);
days=0;
hours=0;
minutes=0;
sec=0;
display(days,hours,minutes,sec);
if (typeof callback === 'function' ) {
callback();
}
}else{
days = parseInt(remaining/86400);
remaining = (remaining%86400);
hours = parseInt(remaining/3600);
remaining = (remaining%3600);
minutes = parseInt(remaining/60);
remaining = (remaining%60);
sec = parseInt(remaining);
display(days,hours,minutes,sec);
}
}
//Function For displaying Results in HTML page with specific ID's
function display(days,hours,minutes,sec) {
var dl = days.toString().length;
if (dl == "1") {
sl = 2;
}else{
if (isNaN(dl)) {
sl = 3;
}
sl = dl;
}
d1="days";
d2=val;
d=d1.concat(d2);
h1="hours";
h2=val;
h=h1.concat(h2);
m1="minutes";
m2=val;
m=m1.concat(m2);
s1="seconds";
s2=val;
s=s1.concat(s2);
document.getElementById(d).innerHTML = ("00"+days).slice(-sl);
document.getElementById(h).innerHTML = ("0"+hours).slice(-2);
document.getElementById(m).innerHTML = ("0"+minutes).slice(-2);
document.getElementById(s).innerHTML = ("0"+sec).slice(-2);
}
}
</script>
<?php
for ($i = 6; $i <9; $i++)
{
$dates="2019-03-0$i 12:45:01";
?>
<script>
countdown('<?php echo $dates;?>',callback,'<?php echo $i;?>');
function callback(){
//alert('Your Id is Expired');
};
</script>
<div class="countDown" align="center">
<span id="days<?php echo $i; ?>">00</span> <!-- Remaining Days,id="days"-->
<span id="hours<?php echo $i; ?>">00</span> <!-- Remaining hours ,id="hours"-->
<span id="minutes<?php echo $i; ?>">00</span> <!-- Remaining minutes,id="minutes"-->
<span id="seconds<?php echo $i; ?>">00</span> <!-- Remaining secounds,id="secounds"-->
</div>
<?php
}
?>
First iterated value only assigned to all other loop ids...Instead of unique values
Loop have 3 iterations
First iteration value assigned first id
The first iteration value assigned to next two iterations..
Kindly help me to fix the issue..
Combination of php and javascript always confusing. It can be used in combination when creating dynamic elements on page load but not after page load.So you have to code in javascript for countdown. If there is need to access server variable (i.e php variable ) then you need Ajax request to access this variable.
Related
I am trying to take the values from the array in PHP, and pass them onto the JavaScript function. The code below functions as intended. The values are taken from a MySQL database and entered into their respective arrays. [Disclaimer: New to coding]
echo "<div id='demo'></div>";
$sql = mysqli_query($conn, "SELECT DISTINCT Safepoint_name,Latitude,Longitude FROM safepoints");
while($row = mysqli_fetch_array($sql)) {
$latl[] = $row['Latitude'];
$long[] = $row['Longitude'];}
foreach($latl as $name) {
echo "$name";
}
foreach($long as $name) {
echo "$name";
}
The problem I am having is with code as shown below. It does not process and show the output as desired. I want the output to be shown one after the other after subtracting the two arrays. I would prefer if the output could be designed via HTML. What am I supposed to do?
[Note: The function is just a trial function just for checking whether it works]
<p id="demo"></p>
<button onclick = "myFunction()">Submit</button>
<script type="text/JavaScript">
let text = "";
function myFunction() {
var latitute = <?php echo json_encode($latl); ?>;
var loni = <?php echo json_encode($long); ?>;
for (let i = 0; i < latitute.length; i++)
{
var x[i] = latitute[i]-loni[i];
text += x[i]+"<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
I think your problem here is that you are defining variable x in a cycle (first warning something is fishy) and you are assigning a value into it's array index at the same time (which is technically possible, but not recommendable, in PHP, but definitely not in JS where is causes syntax error).
You can skip the variable completely and just generate the text.
for (let i = 0; i < latitute.length; i++) {
text += (latitute[i]-loni[i]) +"<br>";
}
Or if you need to keep the result array for later, you should define it as an array before the cycle:
var x = [];
for (let i = 0; i < latitute.length; i++) {
x[i] = latitute[i]-loni[i];
text += x[i]+"<br>";
}
Update:
<p id="demo"></p>
<button onclick = "myFunction()">Submit</button>
<script type="text/JavaScript">
console.log('Preparing JS...');
let text = "";
function myFunction() {
console.log('Calculating demo...');
var latitute = [9,8,7];
var loni = [1,2,3];
for (let i = 0; i < latitute.length; i++) {
text += (latitute[i] - loni[i]) + "<br>";
}
document.getElementById("demo").innerHTML = text;
alert('Demo OK');
}
</script>
JS runs OK after submit.
Right-Click your page and use "View page source file" to check what PHP generates into the JS - if it's really valid array as in the example above.
Then open Debugger (press F12 in browser) and see Console if there are any Syntax or other errors.
If you are in doubt if JS is running, you can add console.log() and/or alert() into your code (see the example).
Good Afternoon,
I need to check if the value insert by the user inside an inputbox on my PHP page it's included in specific range. So if the value insert isn't included in this range i need to color the text in the inputbox or show a message. The range is definited from two PHP variables.
For example if my range will be >10 and <20 any number from 11 to 19 will be 'ok' and any another number (out of this range) will be colored in red or something like this.
I tried to use something like this:
<script>
function checkFilled() {
var inputVal = document.getElementById("myinputbox");
var min = "<?php echo $someVar2; ?>";
var max = "<?php echo $someVar3; ?>";
if (inputVal.value < min) {
inputVal.style.backgroundColor = "yellow";
}
else if (inputVal.value > max) {
inputVal.style.backgroundColor = "yellow";
}
else {
inputVal.style.backgroundColor = "";
}
}
checkFilled();
</script>
PHP:
$someVar2 = 10;
$someVar3 = 20;
echo '<input type="text" id="myinputbox" onchange="checkFilled();">';
This way doesn't work and all number I insert in my inputbox will be change the color to yellow. If I try to set the min and the max variable with a number directly in Javascript (without reading the variable from PHP) the script work.
Could anyone please help me?
Thanks you very much for your help.
Regards
Good Afternoon
you can go this way
<input type="text" id="myinputbox" oninput="myFunction()">
<script>
function myFunction() {
var inputVal = document.getElementById("myinputbox").value;
var min = "<?php echo $someVar2; ?>";
var max = "<?php echo $someVar3; ?>";
if (inputVal.value < min) {
document.getElementById("myinputbox").style.backgroundColor = "yellow";
}
else if (inputVal.value > max) {
document.getElementById("myinputbox").style.backgroundColor = "red";
}
else {
document.getElementById("myinputbox").style.backgroundColor = "";
}
}
</script>
you have to use oninput event and try debugging you will get it
All the best
I have a food ordering script which I want to add If delivery time is between 8:00:00PM - 7:59:59AM to add an extra fee of $5 and if it is between 8:00:00 AM and 7:59:59 PM to keep delivery as is in the script.
This is my code that calculates the delivery fee that returns the delivery fee we already have set in our dashboard.
We want to add this as a fix to add a fee for our night deliveries.
Day deliveries = Normal delivery Fee
Night Delivery = Normal delivery fee + 5
Thank you and I hope someone can guide me.
public static function verifyLocation($merchant_id=0, $lat=0, $lng=0,$order_subtotal=0)
{
$resp = Yii::app()->db->createCommand()
->select('merchant_id,latitude,lontitude,minimum_order')
->from('{{merchant}}')
->where("merchant_id=:merchant_id",array(
':merchant_id'=>(integer)$merchant_id,
))
->limit(1)
->queryRow();
if($resp){
$provider = FunctionsV3::getMapProvider();
MapsWrapper::init($provider);
$unit = FunctionsV3::getMerchantDistanceType($merchant_id);
$mode = isset($provider['mode'])?$provider['mode']:'driving';
$merchant_delivery_distance = getOption($merchant_id,'merchant_delivery_miles');
/*GET DELIVERY FEE*/
$delivery_fee = getOption($merchant_id,'merchant_delivery_charges');
$resp_distance = array();
if($merchant_delivery_distance>0){
$resp_distance = MapsWrapper::getDistance($resp['latitude'],$resp['lontitude'],$lat,$lng,$unit,$mode);
$distance = $resp_distance['distance'];
if($merchant_delivery_distance>0){
if($distance>$merchant_delivery_distance){
$pretty_distance = Yii::t("default","[distance] [unit]",array(
'[distance]'=>$merchant_delivery_distance,
'[unit]'=>MapsWrapper::prettyUnit($unit)
));
$error = Yii::t("default","Sorry but this merchant delivers only with in [distance] your current distance is [current_distance]",array(
'[distance]'=>$pretty_distance,
'[current_distance]'=>$resp_distance['pretty_distance']
));
throw new Exception( $error );
}
}
/*MINIMUM ORDER TABLE*/
$min_tables_enabled = getOption($merchant_id,'min_tables_enabled');
if($min_tables_enabled==1){
$min_order = self::getMinimumOrderTable(
$merchant_id,$resp_distance['distance'],$resp_distance['unit'],$resp['minimum_order']
);
if($min_order>$order_subtotal){
$error = Yii::t("default","Sorry but minimum order is [min_order] for distance [distance]",array(
'[min_order]'=>FunctionsV3::prettyPrice($min_order),
'[distance]'=>$resp_distance['pretty_distance']
));
throw new Exception( $error );
}
}
/*SHIPPING FEE*/
$shipping_enabled = getOption($merchant_id,'shipping_enabled');
if($shipping_enabled==2){
$delivery_fee = self::getShippingFee($merchant_id,$resp_distance['distance'],$resp_distance['unit'],$delivery_fee);
}
}
return array_merge((array)$resp_distance, array('delivery_fee'=>$delivery_fee));
} else throw new Exception( t("Merchant not found") );
}
You could achieve that by using php date to get time between desired time so you can increase the fee accordingly
*Note : PHP gets date from server ,if you were to set the price based on the individual user timezone.Javascript should be used to integrate with PHP
<?php
date_default_timezone_set('Africa/Johannesburg'); //Set your timezone here get php timezone from
https://www.php.net/manual/en/timezones.php
$normalfee = "500"; //The variable containing the normal fee
$tax = "5"; //The added tax for after 8pm fee increase
$getdate = date("Hi"); //Get some time from the server
echo $getdate."Debug : The current time now<br>"; //For debug purposes
if(($getdate > "759") && ($getdate < "2000")){
$finalfee = $normalfee;
echo $finalfee."Debug : Still the same fee<br>"; //The fee should remain normal starting at 8:00am till 7:59:59pm
} else {
$finalfee = $normalfee + $tax;
echo $finalfee."Night time fee added<br>"; //The fee will increase by 5 starting from 8:00pm till 7:59:59am
}
echo "Debug variable passed out of condition the dollar sign can now be added $".$finalfee."<br>";
//Again Debugging this is to show you can then use the $finalfee variable outside the conditions
?>
The script cleaned up...
<?php
date_default_timezone_set('Africa/Johannesburg');
$normalfee = "500";
$tax = "5";
$getdate = date("Hi");
if(($getdate > "759") && ($getdate < "2000")){
$finalfee = $normalfee;
} else {
$finalfee = $normalfee + $tax;
}
$display = "Final price $".$finalfee;
?>
I'm modifying one script and learning JS and Web Sockets while changing it to my needs.
Script is a simple calculator between BTC and USD.
Code works fine, but I cant get proper number formatting since I'm not certain should I do it in JS or PHP.
HTML
<input type="text" class="form-control" id="amtUSD" value="<?php echo $data['price_usd']; ?>">
JS
var ember = [];
var usdInput = document.getElementById("amtUSD");
var btcInput = document.getElementById("amtBTC");
ember.btcPrice = <?php echo $data['price_usd']; ?>;
ember.socket = io.connect('https://socket.coincap.io');
ember.socket.on('trades', function(data) {
var amt = document.getElementById("amtUSD");
if (data.coin == "BTC") {
ember.amtUSD = usdInput.value;
ember.amtBTC = btcInput.value;
ember.usdCalc = ember.amtBTC * data.msg.price;
if(data.msg.price > amt.value) {
$(amt).addClass('increment');
} else {
$(amt).addClass('decrement');
}
$("#amtUSD").attr("value", ember.usdCalc);
setTimeout(function () {
$(amt).removeClass('increment decrement');
}, 700);
}
});
$("#amtBTC").bind("change paste keyup", function() {
ember.usdCalc = $(this).val() * ember.btcPrice;
$("#amtUSD").attr("value", ember.usdCalc);
});
I tried with PHP. It works for the first value, but as soon as it gets new value, it reverts to non formatted value.
<?php echo number_format($data['price_usd'], 2); ?>
So, I presume I need to format numbers in JS or Jquery - it doesnt matter for this case, whichever is simpler.
Thanks in advance
I am using js and php to build an app. I've used a foreach loop in php to create buttons for each row fetched from mysql table. Each button has a unique value (row id).
If someone clicks on of the buttons (each with unique id), there will be a total likes count that holds how many times a button is clicked.
If we have three buttons, and button 1 is clicked, then total likes will be increase by 1. if the same button is clicked again, then the value would decrease by 1.
However, if two buttons of different values are clicked, the total likes add.
When using js, I cant get each button id to pass to the js function loaded from the foreach loop. only the last button value loads to the js function.
Here is what i've tried. the js works but it doesnt apply to each button of the foreach loop.
My Code
<?php foreach($values as $value){
$value['button_id'];
<!-- button --->
<button id="button"
class="button-<?= $value['button_id']; ?>"
value="<?= $value['button_id']; ?>"
onclick="showUser(this.value)" >LIKE
</button>
<!-- button --->
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
Here is an illustration explaining what I mean
Thanks in advance
<script>
var likes = new Array();
function calc(value) {
if(likes[value] == 0 || !likes[value]) {
likes[value]=1;
} else {
likes[value]=0;
}
var sum=0;
for(i=0; i<likes.length; i++) {
if(likes[i]==1){ sum ++ }
}
document.getElementById("total").innerHTML = sum;
}
</script>
<div id=total>0 </div>
<?php
$values = [1,2,3]; //here you can generate values
foreach($values as $value){
?>
<button id="button"
class="button-<?php echo $value; ?>"
value="<?php echo $value; ?>"
onclick="calc(<?php echo $value; ?>)" >LIKE
</button>
<?php
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>