开发者

How to get time from server using ajax?

I am trying to create a website like penny auction how to display the count down time? i tried that using ajax, but sometimes it swallow one or two seconds, it shows seconds like 10,9,7,6,3... i mean it doesn't show the proper count down time.. please help me to solve this problem

here is my code

<?php 
@session_start();
include "includes/common.php";
include_once "includes/classes/class.Auction.php";
$objAuction     = new Auction();
$result=$objAuction -> getStatus();
echo $result;

?>

//ajax code

function getStatusOne(pId)

{

var strURL="get_status_one.php?pId="+pId;
var req = getXMLHTTP();

if (req) 
{           
    req.onreadystatechange = function() 
    {
        if (req.readyState == 4) 
        {   
            if (req.status == 200) 
            {       
                  //alert(req.responseText);
                var result= req.responseText.substr(1).split("|");

                for (var x = 0; x < result.length; x++)
                {

                    var resultN=result[x].split(",");

                    var prId=resultN[0];

                    var temp=resultN[1];
                    var sec=parseInt(temp);


                    var price=resultN[2];
                    //alert(prId+' '+temp+' '+price);
                    var mem=resultN[3];
                    var img=resultN[4];
                    var autobid=resultN[5];
                    if(img=='') {
                        img='images/profile/no_image.jpg'
                    }
                    if(!price)
                    {
                        price='0.00';
                    }
                    if(!mem)
                    {
                        mem='No Bidders Yet';
                    }

                    if(document.getElementById("bid_price"+prId))
                    {   

                        document.getElementById("bid_price"+prId).innerHTML='$'+price;
                        document.getElementById("bidder_name"+prId).innerHTML=mem;
                        document.getElementById("userimg").src=img;
                        document.getElementById("bid_rate").innerHtml=autobid;

                         if(sec<= -1)
                        {

                                sold(prId);
                                if(document.getElementById('end'+pId))
                                {
                                    document.getElementById('end'+pId).style.display="block";
                                }
                                if(document.getElementById('div_bid_image'))
                                {
                                    document.getElementById('div_bid_image').style.display="none";
                                }   
                                if(document.getElementById('clsBidB'+pId))
                                {        开发者_运维问答                               
                                    document.getElementById('clsBidB'+pId).style.display="none";    
                                }
                        } 
                        else {
                            if(document.getElementById('div_bid_image').style.display == "none")
                            {
                                document.getElementById('div_bid_image').style.display="block";
                            }
                            if(sec >=0)
                            {
                                SetCountdownText(sec,"div_timer"+prId,prId);
                            }
                        }
                    }
                }

            } 
            else 
            {
                //alert("There was a problem while using XMLHTTP:\n" + req.statusText);
            }               
        }
    }       
    req.open("POST", strURL, true);

    req.send(null);
}

}

//php code to calculate time

    function getStatus()
{

    $selProd="select a.pdt_id, unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."') as seconds, b.bid_price,c.uname  from tbl_products a left join tbl_auction b on a.pdt_id=b.product_id left join tbl_members c on  b.member_id=c.member_id where(select unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."'))>= 0 ";

    if($this->ExecuteQuery($selProd,"norows") > 0)
    { 

        $auctionArr=$this->ExecuteQuery($selProd,"select");

        $auctionName=$this->array2str($auctionArr);
    }
    return $auctionName;
}

function array2str($array,$level=1) 
{
    $str = array();
    foreach($array as $key=>$value) {
     if(is_int($key))
     {
        $nkey = $key;
        $nvalue = is_array($value)?'|'.$this->array2str( $value ) : $value;
        $str[] = $nvalue;
    }
    }       
     return implode(',',$str);

}


try this

<?php

$target = mktime(0, 0, 0, 14, 07, 2011) ;

$today = time () ;

$difference =($target-$today) ;

$days =(int) ($difference/86400) ;

print "Our event will occur in $days days";

?>


Assuming you have something like a DIV with the ID "countdown" (to display the countdown in):

Example JavaScript (assumes use of jQuery - recommended):

(function(jQuery) {
    updateCountdown("countdown"); // Call on page load
    var countdown = setInterval('updateCountdown("countdown")', 1000); // Update countdown every second
})(jQuery);

function updateCountdown(elementId) {
    jQuery.ajax({       
        url: "/ajax/countdown.php?auctionId=123", 
        type: "GET",
        dataType: "json",
        success: function(response) {
            // Insert value into target element
            jQuery("#"+elementId).html(response["timeRemaining"]);

            // Stop countdown when complete
            if (response["countdownComplete"] == true)
            clearInterval(countdown);
        }
    });
}

Example PHP script (assumed to be at /ajax/countdown.php by the above JavaScript):

<? php
/* Insert your own logic here */
$response["timeRemaining"] = "5 seconds";
$response["countdownComplete"] = false; // Set to true when countdown complete
echo json_encode(response);
?>

I'd recommend doing all the calculation server side (in PHP) as it has really excellent time/date handling (with lots of built in methods) and requires less code to implement overall.


Have a PHP page echo out the countdown time. And then use something like jQuery's AJAX HTTP Request for that page and populate the response in a DOM element somewhere.


Why do you need Ajax to display the countdown time? Why can't you just display it when the page loads along with the rest of the data?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜