Can't solve Javascript Timer - countdowntimer

My timer on this page http://jian.comoj.com/countdown.php isn't counting down. I follow a video tutorial on doing this but somehow something is wrong and I don't know what it is.
<?php
include "connect.php";
$query= "select * from product where product_id='1'";
$result= mysql_query($query);
$record= mysql_fetch_object($result);
$time= $record->end_time;
date_default_timezone_set('Asia/Singapore');
$unix_time= strtotime($time);
?>
<script type="text/javascript">
function countdown(){
<?php
$now= time();
$sec= $unix_time-$now;
$min= $sec/60;
$hour= $min/60;
$sec %= 60;
$min %= 60;
?>
var hour= <?php echo floor($hour); ?>;
var min= <?php echo $min; ?>;
var sec= <?php echo $sec; ?>;
document.getElementById("hour").innerHTML = hour;
document.getElementById("min").innerHTML = min;
document.getElementById("sec").innerHTML = sec;
setInterval('countdown()',1000);
}
</script>
<div id="hour"></div>
<div id="min"></div>
<div id="sec"></div>
<script type="text/javascript">countdown();</script>

function countdown(){
var hour= 3;
var min= 39;
var sec= 58;
document.getElementById("hour").innerHTML = hour;
document.getElementById("min").innerHTML = min;
document.getElementById("sec").innerHTML = sec;
setTimeout('countdown()',1000);
}
LOOK AT THE FUNCTION THEY ARE FIXED i.e hour, min and sec.

Related

Select day of links laravel

I want to make a modal with a select of day that the links are showed... Showing the 10 past days and paginate with scroll... How can I do it? Carbon? If yes, I don't know how, because I'm beginner.
VIEW:
<div class="white-balloon" id="selectday-balloon">
<ul id="selectday-scroll">
<!--current day = 19/02/2018-->
<!--past days-->
<li rel="18/02/2016"><h1>Yesterday</h1></li>
<li rel="17/02/2016"><h1>17/02/2018</h1></li>
<li rel="16/02/2016"><h1>16/02/2018</h1></li>
<li rel="15/02/2016"><h1>15/02/2018</h1></li>
<li rel="14/02/2016"><h1>14/02/2018</h1></li>
<li rel="13/02/2016"><h1>13/02/2018</h1></li>
<li rel="12/02/2016"><h1>12/02/2018</h1></li>
<li rel="11/02/2016"><h1>11/02/2018</h1></li>
<li rel="10/02/2016"><h1>10/02/2018</h1></li>
<li rel="09/02/2016"><h1>09/02/2018</h1></li>
<!--continue in paginate-->
</ul>
</div>
JQUERY LOAD MORE:
$('#selectday-scroll').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
var isLoading = false;
var last_day = $("#selectday-scroll li").last().attr("rel");
if (isLoading === false) {
var isLoading = true;
$.ajax({
url: window.location.origin + '/balloons/selectday/',
dataType: "HTML",
type: 'POST',
data: {last_day: last_day},
beforeSend: function () {
},
success: function (response) {
$('#selectday-scroll').append(response);
var isLoading = false;
}
});
}
}
});
you can use for loop for that, try below code. This code is controller code, you need to add lastDays in view return statement.
$today = Carbon::today();
$lastDays = array();
for ($i = 1; $i < 10; $i++) {
$day = $today->subDays(1)->format('d/m/Y');
$lastDays[] = $day;
}
Try this, at the end you have an array with the dates.
You can change de format like you wnat.
$today = Carbon::now();
$days = 10;
for($i = 0; $i <= $days; $i++)
{
$date = '';
// $date = $today->addDays($i); if you want add day
$date = $today->subDays($i);
$arrayDate[] = $date->format('Y-m-d') ;
}
Carbon Documentation

Restrict zip codes for custom shipping method is not working after hide the shipping method

we are really facing very strange problem here.
we are using 1.9.0.1 and custom shipping method.
We Hide Shipping Method Step in checkout using answer gave by #Marius here :
https://magento.stackexchange.com/questions/53355/remove-shipping-steps-in-onepage-checkout
But we have one problem here.
we allowed only some zip codes to place an order.
but here its allowing for all zip codes when user enter first time.
once user enter zip code and click on "Continue" button, it will go to next step [payment methods]
Payment method step
Than if user again come to Previous step and enter same zip code and if user click on "Continue"
button, than it will show error message in pop up - "Invalid shipping method"
This is fine, but it should not allow when user enter zip code for first time also.
Before everything was fine, once we hide shipping method , this problem happened. but for default shipping method it is working fine.
ex site : link & zip code 000000
we are using this code for restricting zip codes and finding shipping charges.
<?php
class extension_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
/* Use group alias */
protected $_code = 'mpperproductshipping';
public function collectRates(Mage_Shipping_Model_Rate_Request $request){
$postCode = $request->getDestPostcode();
$restrictedCodes = array(
110001,
110002
); //restricted values. they can come from anywhere
if (!in_array($postCode, $restrictedCodes)) {
return false;
}
$result = Mage::getModel('shipping/rate_result');
/* Edited by vikas_mageworx */
$postcode=$request->getDestPostcode();
$countrycode=$request->getDestCountry();
$items=$request->getAllItems();
/* End Editing by vikas_mageworx */
$postcode=str_replace('-', '', $postcode);
$shippingdetail=array();
/* one start */
$shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
/* one end */
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if($mpassignproductId) {
$mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
$partner = $mpassignModel->getSellerId();
} else {
$collection=Mage::getModel('marketplace/product')
->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
foreach($collection as $temp) {
$partner=$temp->getUserid();
}
}
$product=Mage::getModel('catalog/product')->load($proid)->getWeight();
$weight=$product*$item->getQty();
if(count($shippingdetail)==0){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}else{
$shipinfoflag=true;
$index=0;
foreach($shippingdetail as $itemship){
if($itemship['seller_id']==$partner){
$itemship['items_weight']=$itemship['items_weight']+$weight;
$itemship['product_name']=$itemship['product_name'].",".$item->getName();
$itemship['item_id']=$itemship['item_id'].",".$item->getId();
$itemship['qty']=$itemship['qty']+$item->getQty();
$shippingdetail[$index]=$itemship;
$shipinfoflag=false;
}
$index++;
}
if($shipinfoflag==true){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}
}
}
$shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);
if($shippingpricedetail['errormsg']!==""){
Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
return $result;
}
/*store shipping in session*/
$shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
$shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
/* Use method name */
$method->setMethod($this->_code);
$method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
$method->setCost($shippingpricedetail['handlingfee']);
$method->setPrice($shippingpricedetail['handlingfee']);
$result->append($method);
return $result;
}
public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
$shippinginfo=array();
$handling=0;
$session = Mage::getSingleton('checkout/session');
$customerAddress = $session->getQuote()->getShippingAddress();
/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
/* End Editing by vikas_boy */
/* one */
foreach($shippingdetail as $shipdetail) {
$seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
$sellerAddress = $seller->getPrimaryShippingAddress();
$distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
// echo "distance ".$distance;die;
$price = 0;
$itemsarray=explode(',',$shipdetail['item_id']);
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if (Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($proid))
{
continue;
}
$mpshippingcharge = 0;
$localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
$regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
$stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
if(in_array($item->getId(),$itemsarray)) {
if($mpassignproductId) {
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
}
} else {
// echo "imte ".$item->getProductId();
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
// echo "imte ".$item->getProductId();
// echo "ship ".$mpshippingcharge;
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
}
}
/* tt */
// echo "test ".$mpshippingcharge;die;
if(!is_numeric($mpshippingcharge)){
$price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
}else{
$price=$price+($mpshippingcharge * floatval($item->getQty()));
}
}
}
$handling = $handling+$price;
$submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
}
$msg="";
return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
}
/* one end */
/* tt start */
private function getDistanse($origin,$destination) {
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_all = json_decode($response);
$distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
if($distance==0){
$zips = array(
$origin,$destination
// ... etc ...
);
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = json_decode(curl_exec($curl));
$info = curl_getinfo($curl);
if ($info['http_code'] != 200) {
// Request failed
} else if ($data->status !== 'OK') {
// Something happened, or there are no results
} else {
$geocoded[$zip] =$data->results[0]->geometry->location;
}
}
$distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);
}
return $distance;
}
public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)
{
$measure_unit = 'kilometers';
$measure_state = false;
$measure = 0;
$error = '';
$delta_lat = $lat_b - $lat_a ;
$delta_lon = $lon_b - $lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$measure = $distance;
return $measure;
}
}
/* tt end */
onepage.phtml : app/design/frontend/default/em0113/template/checkout/onepage.phml
<div class="page-title">
<h1><?php echo $this->__('Checkout') ?></h1>
</div>
<script type="text/javascript" src="<?php echo $this->getJsUrl('varien/accordion.js') ?>"></script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('js/opcheckout.js') ?>"></script>
<ol class="opc" id="checkoutSteps">
<?php $i=0; foreach($this->getSteps() as $_stepId => $_stepInfo): ?>
<?php if (!$this->getChild($_stepId) || !$this->getChild($_stepId)->isShow()): continue; endif; $i++ ?>
<li id="opc-<?php echo $_stepId ?>" class="section<?php echo !empty($_stepInfo['allow'])?' allow':'' ?><?php echo !empty($_stepInfo['complete'])?' saved':'' ?>">
<div class="step-title">
<span class="number"><?php echo $i ?>.</span>
<h2><?php echo $_stepInfo['label'] ?></h2>
<?php echo $this->__('Edit') ?>
</div>
<div id="checkout-step-<?php echo $_stepId ?>" class="step a-item" style="display:none;">
<?php echo $this->getChildHtml($_stepId) ?>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">
//<![CDATA[
var accordion = new Accordion('checkoutSteps', '.step-title', true);
<?php if($this->getActiveStep()): ?>
accordion.openSection('opc-<?php echo $this->getActiveStep() ?>');
<?php endif ?>
var checkout = new Checkout(accordion,{
progress: '<?php echo $this->getUrl('checkout/onepage/progress') ?>',
review: '<?php echo $this->getUrl('checkout/onepage/review') ?>',
saveMethod: '<?php echo $this->getUrl('checkout/onepage/saveMethod') ?>',
failure: '<?php echo $this->getUrl('checkout/cart') ?>'}
);
//]]>
</script>
What you can do is bind a javascript event to the input field of pincode and send the request everytime when someone is typing in the pincode like this:
<input type = "text" onchange = "myfun(this.value)">
And then bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value once you finish typing into the text box
Otherwise you can also go with
<input type = "text" onkeypress = "myfun(this.value)">
And then again bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value even when you are typing into the text box
Ok, in your onepage template, write this code:
jQuery('#billing:postcode').change(function(){
// your ajax call to your controller where you are verifying your pincode, something like:
jQuery.ajax({
url: "path/to/your/controller",
data: this.value,
success: function(response){
if(response == true){
// your success action
} else{
//your failure action
}
}
})
})

Need help in clearTImeout

Ajax
<script type="text/javascript">
var stopTime =0;
var scoreCheck = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkScoreRoundOne',
success:function(output){
if(output !='Instruction'){
console.log(output);
clearTimeout(scoreCheck);
}
else
console.log(output);
stopTime = setTimeout(scoreCheck, 1000);
}
});
}
stopTime = setTimeout(scoreCheck,1000);
</script>
Controller
public function checkScoreRoundOne(){
$id = $this->session->userdata('userID');
$battleID = $this->lawmodel->getBattle($id);
foreach($battleID as $row){
$Rscore = $row->requestedScore;
$Cscore = $row->challengerScore;
if($Cscore == '1'){
$rID = $this->lawmodel->getID($row->challengerID);
foreach($rID as $row){
echo $row->username."Got the correct answer";
}
}
else if($Rscore == '1'){
$cID =$this->lawmodel->getID($row->requestedID);
foreach($cID as $row){
echo $row->username."Got the correct answer";
}
}
else
echo "Instruction";
}
}
Im confused in the code above
In ajax, why when the output !='Instruction' it will display "Instruction" and when the output == 'Instruction' it will display $row->username got the correct answer.
And how can i stop the setTimeout when the Cscore == 1 or Rscore ==1?
I think cleartimeout will not just stop the setTimeout..
Plss help...Im new in ajax..
Im using codeigniter
About the clearTimeout:
clearTimeout(stopTime);

Remove items from cart after 30 minutes - Magento

I would like to remove items from cart for both logged in and guest shoppers.
I have set the Cookie Session timeout to 1800 which solves the guest shoppers but under quote lifetime I can only select 1 day. Anyway to get this to 30 mins?
I changed:
$lifetimes = Mage::getConfig()->getStoresConfigByPath('checkout/cart/delete_quote_after');
foreach ($lifetimes as $storeId=>$lifetime) {
$lifetime *= 86400;
}
to
$lifetimes = Mage::getConfig()->getStoresConfigByPath('checkout/cart/delete_quote_after');
foreach ($lifetimes as $storeId=>$lifetime) {
$lifetime *= 1800;
}
then set 1 day under quote life time. Still no joy.
I would say create a module that adds an expiration time to the quote item and then checks each for that expiration time. Something along the lines of
class My_Module_Model_Observer
{
/* observes sales_quote_add_item */
public function addItemExpiration(Varien_Event_Observer $event)
{
$item = $event->getItem();
$itemExpiration = Mage::getModel('catalog/session')->getQuoteItemExpiration();
if (!$itemExpiration)$itemExpiration = array();
$itemExpiration[$item->getId()] = (time() + (30 * 60));
Mage::getModel('catalog/session')->setQuoteItemExpiration($itemExpiration);
}
/* observes sales_quote_load_after */
public function removeExpiredItems(Varien_Event_Observer $event)
{
$itemExpiration = Mage::getModel('catalog/session')->getQuoteItemExpiration();
foreach ($event->getQuote()->getAllItems() as $item) {
if ($itemExpiration[$item->getId()] < time()) {
$event->getQuote()->removeItem($item->getId());
}
}
}
}
Note that I have not tested this and simply coded it by memory and so it might not work without some modification
here is one more solution you can try
paste this code in sidebar.phtml
<?php if ($this->helper('customer')->isLoggedIn()) {
$session = Mage::getSingleton('checkout/cart');
if ($session['quote']) {
$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
$qtyCart = (int) $cart['items_qty'];
if ($qtyCart > 0) {
$updateAt = $session['quote']->getUpdatedAt(); // cart update date
$currentDate = strtotime($updateAt);
$futureDate = $currentDate + (60 * 20); //target date
$date1 = date("Y-m-d H:i:s");
$date1 = strtotime($date1); // current date
//$futureDate = date();
$dateFormat = "d F Y -- g:i a";
$targetDate = $futureDate; //Change the 25 to however many minutes you want to countdown
$actualDate = $date1;
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff / 60 / 60 / 24);
$remainingHour = floor(($secondsDiff - ($remainingDay * 60 * 60 * 24)) / 60 / 60);
$remainingMinutes = floor(($secondsDiff - ($remainingDay * 60 * 60 * 24) - ($remainingHour * 60 * 60)) / 60);
$remainingSeconds = floor(($secondsDiff - ($remainingDay * 60 * 60 * 24) - ($remainingHour * 60 * 60)) - ($remainingMinutes * 60));
$actualDateDisplay = date($dateFormat, $actualDate);
$targetDateDisplay = date($dateFormat, $targetDate);
?>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: "GET",
url: "<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . 'index.php/countdowncont/'; ?>",
async: true,
success: function(data){
var data = data.split("/");
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
document.getElementById("remain").style.display = "block";
document.getElementById("remain").innerHTML = " Items reversed for <span> "+minutes+":"+seconds+"</span> minutes.";
SD=window.setTimeout( "setCountDown()", 1000 );
}else{
document.getElementById("remain").innerHTML = "";
seconds = "00"; window.clearTimeout(SD);
jQuery.ajax({
type: "GET",
url: "<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . 'index.php/countdown/'; ?>", // this the path of your controller
async: false,
success: function(html){
}
});
document.getElementById("remain").innerHTML = "";
//window.location = document.URL; // Add your redirect url*/
}
}
</script>
<?php if ($date1 < $futureDate && ($qtyCart > 0)) { ?>
<script type="text/javascript">
setCountDown();
</script>
<?php } else {
foreach(
Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection()
as $item ){
Mage::getSingleton('checkout/cart')->removeItem( $item->getId() )->save();}
?>
<style>
#remain{display:none;}
</style>
<?php
}
}
}
} ?>
Now create a controller and assign it to the ajax url and past the following code to that controller
public function indexAction() {
$cartHelperAjax = Mage::helper('checkout/cart');
$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
$qtyCart = (int)$cart['items_qty'];
if($qtyCart > 0){
$updateAt = $cartHelperAjax->getQuote()->getUpdatedAt(); // cart update date
$currentDate = strtotime($updateAt);
$futureDate = $currentDate+(60*20);//target date
$date1 = date("Y-m-d H:i:s");
$date1 = strtotime($date1); // current date
//$futureDate = date();
$dateFormat = "d F Y -- g:i a";
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown
$actualDate = $date1;
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
echo $total_remainTime = $remainingDay ."/".$remainingHour."/".$remainingMinutes."/".$remainingSeconds;
}
}
by these line of code can create a countdown timer. and after particular time the all items from cart will removed.
set timeout from Admin > System > Configuration > Web > Session Cookie Management > Cookie Lifetime
Please try this code to remove last day cart items :
<?php
mb_internal_encoding('UTF-8');
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../app/Mage.php';
Mage::app('admin');
$STORE_ID = 0;
Mage::app()->setCurrentStore($STORE_ID);
$lifetime = 3600;
$quoteCollection = Mage::getModel('sales/quote')
->getCollection()
->addFieldToFilter('created_at', array('to' => date("Y-m-d H:i:s", time() - $lifetime)))
->addFieldToFilter('is_active', 1);
//print_r($quoteCollection);
//echo count($quoteCollection);
//die;
// $date = date('Y-m-d H:i:s');
//echo date("Y-m-d H:i:s", time() - $lifetime) . '<br><br>';
foreach ($quoteCollection as $item) {
$item->delete();
}
echo PHP_EOL . "All process completed now." . PHP_EOL;
?>

Need help debugging Asynchronous AJAX call from a form in a div element to update same div with processed results based on form data

I am using a Mediawiki based website. The site is http://www.DragonFallRPG.com The widget in question is the 'Orion's Dice Box' in the left column of the site.
Not sure if that has any bearing on this but here goes. I have a custom div called 'dice' with a content destination div called 'result'. Below the 'result' div is a form for selecting a number of dice, and the number of sides for those dice. There is a processing script, which is tested working to provide a randomized result as if those dice were thrown. The problem is in the calling of one or more functions, I think. I found the AJAX method for getting the user input via 'get' somewhere on the web and no longer have any idea where it came from. I will include the files below.
dice_header.php (include file for <head> portion of webpage)
<style>
<!--[if IE] -- long buttons / button width in IE fix>
<style>.button{width:1;}</style>
<![endif]-->
</style>
<?php $javafile = dirname(__FILE__).'/ajax_engine.js'; ?>
<script type="text/javascript" src= "<?php echo $javafile ?>" ></script>
<script type="text/javascript">
function submit_dice() {
// Get form values
var no_of_dice = document.getElementById('dice').value;
var no_of_sides = document.getElementById('sides').value;
// Construct URL
<?php $handlerfile = dirname(__FILE__).'/handler.php' ?>
url = '<?php echo $handlerfile; ?>' + '?no_of_dice=' + escape(no_of_dice) + '&no_of_sides=' + escape(no_of_sides);
var xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
alert('Handlerfile URL = ' + url + '\r\n\r\n Escape URL = ' + escape(url) + '\r\n\r\n # of dice = ' + no_of_dice + '\r\n # of Sides = ' + no_of_sides);
alert('url for ajax_get = ' + url);
ajax_get (url, 'result');
}
</script>
The above code is an include in the header of the index.php
The function call for ajax_get seems to be where it breaks down in the process in the above code. I don't know if it requires the http portion of the url or not. I don't know if the escape url is required or not. I'm hesitant to monkey with the script any further without guidance.
The code that follows is the div block for the widget I'm trying to create
dice.php (include file for my widget / div block)
<div id="result" style="text-align:center;
word-wrap: break-word;
width:100px;
font-weight:bold;
font-size:large;
border:1px blue solid;
margin:0;">
<?php
//$filename = dirname(__FILE__).'/ajax_engine.js';
//$handlerfile = dirname(__FILE__).'/handler.php';
if (file_exists($handlerfile)) {
echo "Handler file path OK";
echo 'alert(\'Handler file path = "' . $handlerfile . '"\');';
die();
} else {
echo "BAD handler file path!";
}
?>
</div>
<table border="0" cellspacing="0" cellpadding="0" style="margin:0; padding:0px;" >
<tr>
<td><select name="dice" id="dice" size="1" style="margin:0px;">
<?php
for ($i = 1; ; $i++) {
if ($i > 20) {
break;
}
if ($i == 1) {
echo "<option value=$i selected>$i</option>\n";
} else {
echo "<option value=$i>$i</option>\n";
}
}
?>
</select></td>
<td><select name="sides" id="sides" size="1" style="margin:0px;">
<option value="4">d4</option>
<option value="6">d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20" selected>d20</option>
<option value="100">d100</option>
</select>
</td>
</tr><tr>
<td colspan="2">
<input type="button" onclick="submit_dice();" value="Roll Dice" style="width:100px;" />
</td></tr>
</table>
<!--
Psuedo vs. True Random Numbers
http://www.phpfive.net/pseudo-random_php_functions_and_truly_random_number_generators_article2.htm
-->
Next follows the javascript engine I'm using to begin the AJAX functionality... Mediawiki has it's own built in AJAX - but I have no familiarity with it and tried finding a less complicated working version else where that I could tweak - resulting in this headache.
Several alert popup calls made to help with debugging, but I'm lost, and none of these alerts are actually being called... I can't tell why.
// JavaScript Document "javascript_engine.js"
// Get base url
url = document.location.href;
var base_url = "http://";
alert('base_url = ' + base_url);
xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
var ajax_get_error = false;
alert('ajax_engine.js called');
function ajax_do (url) {
// Does URL begin with http?
alert('url.substring(0, 4) = ' + url);
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create new JS element
var jsel = document.createElement('SCRIPT');
jsel.type = 'text/javascript';
jsel.src = url;
// Append JS element (therefore executing the 'AJAX' call)
document.body.appendChild (jsel);
return true;
}
function ajax_get (url, el) {
// Has element been passed as object or id-string?
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
// Valid el?
if (el == null) { return false; }
alert(url.substring(0, 4));
// Does URL begin with http?
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create getfile URL
getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
// Do Ajax
ajax_do (getfile_url);
return true;
}
Following is getfile.php
<?php //getfile.php -- used for addressing visual part of code
// Get URL and div
if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
// echo 'alert(\'URL in getfile.php = \'); $url';
// Make sure url starts with http
if (substr($url, 0, 4) != 'http') {
// Set error
echo 'alert(\'Security error; incorrect URL!\');';
die();
}
// Try and get contents
$data = #file_get_contents($url);
if ($data === false) {
// Set error
echo 'alert(\'Unable to retrieve "' . $url . '"\');';
die();
}
// Escape data
$data = str_replace("'", "\'", $data);
$data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
$data = str_replace ("\r\n", '\n', $data);
$data = str_replace ("\r", '\n', $data);
$data = str_replace ("\n", '\n', $data);
?>
el = document.getElementById('<?php echo $el; ?>');
el.innerHTML = '<?php echo $data; ?>';
Following is the form processor, generating the random numbers result for the AJAX output/update.
<?php // handler.php
/////////////////////////////////////////////////////////////////
// Random Dice Value Generator v1.0 //
// http://www.dragonfallrpg.com //
// Orion Johnson Copyright 2007 //
// //
// This script is used to create a random number based //
// values from the user's input //
/////////////////////////////////////////////////////////////////
/* double rolldice(int, int)
* - generates a random value based on the numbers passed as an argument
* - maximum iterations = 20 (can be changed in the user form)
* - maximum number of sides per function call = 4, 6, 8, 10, 12, 20, or 100 (can be changed)
*
* Usage: To generate a random total value as if one had thrown that many dice:
* Note: Future revisions may include the ability to add additional lines to the user form
* to mix types of simulated dice being thrown.
*
* array $no_of_dice(x-1); array value "x" taken from user form
* var $no_of_sides; value taken from user form
* var $total_value; sum of values from entire array
* echo $total_value;
*/
// Check variables
if (empty($_GET['no_of_dice'])) {
die ('<span style="color:red;">Number of dice value invalid!</span>');
}
if (empty($_GET['no_of_sides'])) {
die ('<span style="color:red;">Number of sides value invalid!</span>');
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 1000003);
}
function rolldice()
{
$total_value = 0; /* sum of values from entire array */
srand(make_seed()); /* seed random number generator // 1,000,003 is a prime number */
/* start loop structure from 0 to $no_of_dice */
for($i = 0; $i < $_GET['no_of_dice']; $i++)
{
$randnum = rand(1, $_GET['no_of_sides']);
$total_value = $total_value + $randnum;
}
/* end loop */
/* print/return results to the screen */
// echo 'Total value for dice: ' + rolldice();
return $total_value;
}
// Taken from http://www.sebflipper.com/?page=code&file=password.php
// for array iteration see also: http://www.php-scripts.com/php_diary/122799.php3
?>
If there is a simpler way to perform a div update with a random result based on form input, I'm all ears. This has been a headache for too long for me. I'm no code-head, just know enough to tinker and make some things work and understand most things when explained.
I haven't read through all the code, but since MediaWiki 1.17.0 there's a feature called ResourceLoader (if you have older version you should upgrade), which you can use for this purpose.
You can make the whole code into an extension to have it organized in a directory (let's say extensions/DiceBox). The DiceBox.php file in that folder would then be along these lines:
<?php
if( !defined( 'MEDIAWIKI' ) ) {
die();
}
$wgExtensionFunctions[] = 'DiceBoxInit';
$wgHooks['SkinTemplateToolboxEnd'][] = 'DiceBoxOnSkinTemplateToolboxEnd';
$wgResourceModules['ext.DiceBox'] = array(
'localBasePath' => dirname( __FILE__ ),
'remoteExtPath' => 'DiceBox',
'scripts' => 'ext.DiceBox.js',
'dependencies' => 'jquery'
);
function DiceBoxInit() {
global $wgOut;
$wgOut->addModules( 'ext.DiceBox' );
}
?>
<?php
function DiceBoxOnSkinTemplateToolboxEnd() {
$sides = array( 4, 6, 8, 10, 12, 20, 100 );
?>
</ul>
</div>
</div>
<div class="portlet" id="p-dicebox">
<h5>Orion's Dice Box</h5>
<div class="pBody">
<div id="dice-result" style="display: none;"></div>
<form id="dice-form">
<select name="no_of_dice">
<?php
for( $i = 1; $i <= 20; $i++ ) {
echo '<option value="', $i, '">', $i, '</option>';
}
?>
</select>
<select name="no_of_sides">
<?php
foreach( $sides as $n ) {
echo '<option value="', $n, '">d', $n, '</option>';
}
?>
</select>
<input type="button" value="Roll Dice" id="dice-roll" />
</form>
<?php
return true;
}
This code outputs the code box HTML in the sidebar and registers the following JavaScript file (ext.DiceBox.js) to be available on the page:
jQuery( document ).ready( function( $ ) {
$( '#dice-roll' ).click( function() {
$.get( mw.config.get( 'wgExtensionAssetsPath' ) + '/DiceBox/handler.php',
$( '#dice-form' ).serialize(), function( data )
{
$( '#dice-result' ).html( data ).append( '<hr />' ).show();
} );
} );
} );
This code simply uses jQuery (which is bundled with MediaWiki as of 1.16.0) to send a request to the server when the button is clicked and displays the result in the box.
In the handler.php file, there's no place where the random number gets output, so you need to add echo rolldice(); before the ?>.
Finally, to make the extensions fully work, add require_once $IP . '/extensions/DiceBox/DiceBox.php'; to the bottom of LocalSettings.php.

Resources