在jQuery事件上更新MySQL表

时间:2012-06-16 05:26:55

标签: jquery mysql

我有一个从1小时倒数到零的计时器。当它达到零时,jQuery会触发一个事件(下面的代码)。

我需要将数据库表更新为当前的-1。 (例如,如果表的数值设置为20,倒计时到零后,它变为19,依此类推。)

我的问题是 - 如何基于jQuery函数以这种方式更新MySQL数据库?我尝试过使用PHP,但它会立即更新表格,而不是倒计时到零时。 (我已经尝试过这样做了,我现在意识到PHP是服务器端,jQuery是客户端,但我仍然不知道如何制作这样的工作)。

非常感谢你的帮助!

  <script type="text/javascript">



var year=2012;        //Set initial values for timer
var month=06;          
var day=16;           
var hour=17;          
var minute=10;        
var tz=+12;            


var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function countdown(yr,m,d,hr,min){
    theyear=yr;themonth=m;theday=d;thehour=hr;theminute=min;
    var today=new Date();
    var todayy=today.getYear();
    if (todayy < 1000) {
    todayy+=1900; }
    var todaym=today.getMonth();
    var todayd=today.getDate();
    var todayh=today.getHours();
    var todaymin=today.getMinutes();
    var todaysec=today.getSeconds();
    var todaystring1=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
    var todaystring=Date.parse(todaystring1)+(tz*1000*60*60);
    var futurestring1=(montharray[m-1]+" "+d+", "+yr+" "+hr+":"+min);
    var futurestring=Date.parse(futurestring1)-(today.getTimezoneOffset()*(1000*60));
    var dd=futurestring-todaystring;
  //  var dday=Math.floor(dd/(60*60*1000*24)*1);
    var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
    var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
    var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
    if(dhour<=0&&dmin<=0&&dsec<=0){

      //--TIMER REACHES ZERO HERE. Code needed to update MySQL would go here?

    }
    else {
        document.getElementById('count2').style.display="none";
      // document.getElementById('dday').innerHTML=dday;
        document.getElementById('dhour').innerHTML=dhour;
        document.getElementById('dmin').innerHTML=dmin;
        document.getElementById('dsec').innerHTML=dsec;
        setTimeout("countdown(theyear,themonth,theday,thehour,theminute)",1000);
    }
}
</script>

PS。这是我尝试用来更新数据库表的PHP代码:

<?php
        include("db.php");
        mysql_select_db("myData") or die(mysql_error());
        mysql_query("UPDATE cards SET buy=0.01 WHERE id='67'") or die(mysql_error());
        ?>

1 个答案:

答案 0 :(得分:0)

You have to use $.ajax ([http://api.jquery.com/jQuery.ajax/][1]) to do it because jQuery alone do not have access to the database on the server.
In your javascript code inside the if :     

if(dhour<=0&&dmin<=0&&dsec<=0){

      //--TIMER REACHES ZERO HERE. Code needed to update MySQL would go here?

      $.ajax({ 
          url: "pathToYourPHPUpdateScript.php",
          type: "POST",
          success: function(){
            alert("MYSQL UPDATED!");
          }
      });

    }