PHP Countdown distribution - javascript

I am writing a randomized countdown that show number of products left in promotion alongside a timer. Number of products left is stored in the database, so all users see the same number. I am using simple php/ajax/javascript solution. My problem is with distributing the random sales so all fit within limited timer and are nicely distributed.
Here is code I have so far:
function start() {
$date= new DateTime();
$prod_left = getval("SELECT * FROM counter LIMIT 1");
if ( $prod_left == 20 ) {
$fp = fopen("../index.html", "r+");
while($buf = fgets($fp)){
if(preg_match("/<!--(.|\s)*?-->/", $buf)){
fputs($fp, '<script type="text/javascript">$(document).ready(function() {$(".countdown").circularCountdown({startDate:"' . $date->format('Y/m/d H:i:s') . '",endDate:"' . $date->modify("+5minutes")->format('Y/m/d H:i:s') . '",timeZone:+2});});</script></body></html>');
}
}
fclose($fp);
sleep(30);
while ($prod_left > 0) {
if (rand(0,4) > 2) {
$prod_left--;
sleep(rand(1,13));
updateval($prod_left);
}
}
} else {
echo 'Promocja w trakcie lub zakończona, zresetuj zegar, jeżeli chcesz rozpocząć ponownie';
}
exit;
}
My assumption here is: 50% of time decrease timer and wait on average 6.5 seconds, which should on average give me 260 seconds for full sale. Unfortunately its very unevenly distributed. My goal is to have the sale completed not later than 270seconds after start. Will you be able to help?
Implementation doesnt need to be in any particular programing language, im just looking for a clue/concept I can follow to achieve this.
What is the strangest, the $prod_left value not always goes to 0, on sime iterations it just sits at 3 or 5.
Please help!

Related

use php function in javascript

<script>
$(document).ready(function () {
var oMain = new CMain({
win_occurrence: 40, //WIN PERCENTAGE.SET A VALUE FROM 0 TO 100.
slot_cash: 200, //THIS IS THE CURRENT SLOT CASH AMOUNT. THE GAME CHECKS IF THERE IS AVAILABLE CASH FOR WINNINGS.
bonus_occurrence: 15, //SET BONUS OCCURRENCE PERCENTAGE IF PLAYER GET A WIN. SET A VALUE FROM 0 TO 100. (IF 100%, PLAYER GET A BONUS EVERYTIME THERE IS A WIN).
min_reel_loop: 1, //NUMBER OF REEL LOOPS BEFORE SLOT STOPS
reel_delay: 0, //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 $kullanici_bilgileri->bakiye ?>, //STARING CREDIT FOR THE USER
min_bet: 0.05, //MINIMUM COIN FOR BET
max_bet: 0.5, //MAXIMUM COIN FOR BET
max_hold: 3, //MAXIMUM NUMBER OF POSSIBLE HOLD ON REELS
perc_win_prize_1: 50, //OCCURENCE PERCENTAGE FOR PRIZE 1 IN BONUS
perc_win_prize_2: 35, //OCCURENCE PERCENTAGE FOR PRIZE 2 IN BONUS
perc_win_prize_3: 15, //OCCURENCE PERCENTAGE FOR PRIZE 3 IN BONUS
num_symbol_bonus: 3, //NUMBER OF BONUS SYMBOLS (DEFAULT IS SYMBOL 9) THAT MUST BE SHOWN TO ACHIEVE THE BONUS PANEL
num_spin_ads_showing: 10 //NUMBER OF SPIN TO COMPLETE, BEFORE TRIGGERING AD SHOWING.
//// THIS FUNCTIONALITY IS ACTIVATED ONLY WITH CTL ARCADE PLUGIN.///////////////////////////
/////////////////// YOU CAN GET IT AT: /////////////////////////////////////////////////////////
// http://codecanyon.net/item/ctl-arcade-wordpress-plugin/13856421 ///////////
});
</script>
Hello, here is the code I wanna use PHP function in this JavaScript.
money: <?php $kullanici_bilgileri->bakiye ?>
I wrote it like this but that is not working for me.
To print any text in PHP you should use the echo or print function. So this line:
<?php $kullanici_bilgileri->bakiye ?>
Should be:
<?php echo $kullanici_bilgileri->bakiye; ?>
Edit: As far as I know is that you can't pass a PHP string without using the quotes in your javascript code otherwise you will get errors like
Uncaught SyntaxError: Unexpected identifier
So replace:
money: <?php $kullanici_bilgileri->bakiye ?>
With this:
money: '<?php echo $kullanici_bilgileri->bakiye; ?>',
As #Variable pointed out. if you would like to output a string, you will need to add quotes around it.
An alternative to have a proper typecast in JS is using json_encode, example:
{
...
money: <?php echo json_encode($kullanici_bilgileri->bakiye) ?>,
...
}
With this approach, you don't need to worry about forgetting the quotes.

Slideshow Gallery with PHP and Javascript

Hi there I want to create Slideshow Gallery using PHP and Javascript.
I have a camera setup at my house that is sending picture in JPG format every time when motion is detected.
I want to be able when I visit:
camera.example.com/
Pictures from last 3 Days to start to appear in A slideshow fast.
The structure is like this:
camera.example.com
-snap (where the pictures from the camera are uploaded when motion is detected).
code of index.php:
<?
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="snap") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo '<img src="snap/'.$file .'" /><br />';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo '<a href=./slideshow.php>WHEN ALL OF THE PICTURES LOAD UP << CLICK ME >></a><br /><br /><br />';
returnimages() //Output the array elements containing the image file names
?>
code of getimages.php:
<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="snap") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
code of: slideshow.php
<html>
<head>
<title>Timelapse</title>
</head>
<body bgcolor="#000" align="center">
<script src="getimages.php"></script>
<script type="text/javascript">
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "snap/"+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
window.onload=function(){
setInterval("rotateimages()", 500)
}
</script>
<div>
<img id="slideshow" src="loader.gif" />
</div>
</body>
</html>
Please help me with this, it doesn't neccesery have to be even my code.. all I want is to work so if someone gives me a better alternative it's fine.
I want to be able to view what happen on my Front yard during the past 3 days fast, without having to Open all pictures one by one.
I want them SORTED from the Newest to the Oldest.
I used the following tutorial to do this: Slideshow Gallery loading all images in directory
Thank you!
If you can edit the way your images are saved to date_something.jpg then you can use the following. You will have to work out how to place this into your own source code, I wouldn't want to do all the work for you.
If it isn't possible for you to change the way image names are saved, please edit your question and display how your images are saved.
Date format: Year Month Day => 20150415
The following is going by today's date: 15th April 2015.
<?php
// Temporary Array of image names (demo use).
$ImageNames=array("20150415_one.jpg","20150414_two.jpg","20150413_three.jpg","20150412_four.jpg","20150411_five.jpg","20150410_six.jpg");
// Empty Array - To hold image names within date range
$ReturnImages=array();
// For each value in $ImageNames array
foreach ($ImageNames as $Image) {
// Split the image name to get the date
$Uploaded=explode("_",$Image);
/*
$Uploaded[0] => Date
$Uploaded[1] => one.jpg / two.jpg / three.jpg
*/
// If image date is equal to or greater than.
if($Uploaded[0]>=date('Ymd', strtotime('-3 day'))){
array_push($ReturnImages, $Image);
}
}
/* $ReturnImages now holds all the images within the date range (Last 3 days) */
//*********************************************************
// This foreach isn't required, this is to show the results
foreach ($ReturnImages as $display) {
echo $display.' ';
}
//*********************************************************
?>
Output: 20150415_one.jpg 20150414_two.jpg 20150413_three.jpg 20150412_four.jpg
20150411_five.jpg & 20150410_six.jpg will not return because the dates are more than 3 days old.
As you can see I have added comments to explain every step, if you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!

display 125 words from the description field of the database mysql

Hello fellow Overflows,
So im in the middle of creating a toplist script, ready to launch to the public,
I'm stuck on one perticualr subject.
Displaying X amount of content from A database field.
<?php echo $server_data['description']; ?>
As you can see in this image below, That wouldn't be a good idea to display the full amount.
http://i.imgur.com/IhLs7L7.png
What do i need?
Instead of it displaying all of the database field, i just want it to display 150 characters of the field.
It is best to limit characters while you are selecting from database because it will improve performance a bit. You can limit characters on select with mysql LEFT() function.
Here is how to do it:
SELECT LEFT(description, 150), another_col FROM ......
Try this:
$string = substr($server_data['description'], 0, 150);
substr() will only return a certain amount of characters. If you want a certain amount of words then you could use the following:
<?php
function excerpt($content = '',$number_words = 125){
$content = strip_tags($content);
$contentWords = substr_count($content," ") + 1;
$words = explode(" ",$content,($number_words+1));
$excerpt = join(" ",$words);
return $excerpt;
}
echo excerpt($server_data['description'], 125);

Fire Javascript alert when counter reaches 10 minutes

I have a page that updates whenever another entry is added to the database. It displays the timestamp, and then starts counting up using jQuery, along with moment.js to help with time formatting. This is the code for that:
$(function () {
var austDay = new Date('".$array['dateAdded']."');
$('#since".$array['id']."').countdown({since: austDay, significant: 1, layout: '{d<}{dn} {dl} {d>}{h<}{hn} {hl} {h>}{m<}{mn} {ml} {m>}{s<}{sn} {sl}{s>}'});
});
I need to be able to fire an alert whenever a given entry is 10 minutes past the timestamp date and time. I assume the script would need to continually check to see if that's the case. Any help would be greatly appreciated.
This is the solution I came up with for this problem, using a mix of Javascript and PHP.
$now = date("Y-m-d h:i:s");
$plusTen = date("Y-m-d, h:i:s", strtotime("+10 minutes", strtotime($array['dateAdded'])));
$difference = strtotime($plusTen) - strtotime($now);
$difference = round($difference,2) * 1000;
if($difference > 0){
echo '<script type="text/javascript">
setTimeout(function(){staleAlert();}, '.$difference.')
</script>';
}

javascript .keyup correct price formatting and more

So far I have this which is comprised of snippets. I am not an expert in JavaScript by far so if anyone could help me achieve the following I would be very grateful and hopefully learn something new today :)
I want to achieve the following:
When a user types 1000000 into the input field the results shown are as follows,
Higher than $1 million
Lower than $1 million
Between $970 thousand and $1.3 million
Currently I can achieve the correct display of digits to prices but don't know how to add the word million, thousand, hundred to the end of the prices. Plus I'm not sure how to subtract 3% and add 3% to the price for the between price part.
Here is my code so far:
<input type="text" id="price" class="liveprice" value="<?php echo $myprice; ?>" >
<p>Higher than <span id="higher"><?php echo $myprice;?></span></p>
<p>Lower than <span id="lower"><?php echo $myprice;?></span></p>
<p>In between <span id="between"><?php echo $myprice;?></span></p>
<script type="text/javascript">
// make sure it adds commas and dots to price
$.fn.digits = function() {
return this.each(function() {
$(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
// update in real time
$("input.liveprice").keyup(function() {
var value = $(this).val();
$("#higher").text(value).digits();
$("#lower").text(value).digits();
$("#between").text(value).digits();
}).keyup();
</script>
If you want to know if it is higher than 1 million, divide the number by 1 million and then round the number using Math.floor(). If the answer is higher than zero then that is "how many million" you have. You can then insert the word million using something like (you'll need to add some stuff here):
var val = $('your input').val()/1000000;
if (Math.floor(val) > 0) {
$('your element with words').text( val + " million" );
}
Do the same for 1000 but just divide by 1000 instead of 1000000.

Categories

Resources