2013-04-24 124 views
-1

我想使用jQuery的日期選擇器選擇一個日期,那麼當選擇它從數據庫中根據選定的日期 我已經尋求關於做選擇查詢,發現這個問題 jQuery datepicker with php and mysql 他們說我應該使用AJAX做 ,但我不明白他們在做執行! 任何人可以幫助請 我嘗試做這樣的事情jQuery的日期選擇器UI

<script> 

$(function() { 

    $("#datepicker").datepicker({minDate: 0, showAnim: "bounce", 
    onSelect: function(dateText, inst) {<?php mysql_select_db($database_conn, $conn); 
$query_time = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date='"?>dateText<?php "'" ; 
$time = mysql_query($query_time, $conn) or die(mysql_error());</script> 
+0

當PHP使用這樣的,它運行在服務器上創建的頁面時,不能反應到什麼用戶確實在瀏覽器上。你必須使用AJAX - 查看'$ .ajax'和'$ .get'。 – Barmar 2013-04-24 18:39:24

回答

0

更改您的JS送的ONSELECT Ajax調用,傳遞dateText

$("#datepicker").datepicker({ 
    minDate: 0, 
    showAnim: "bounce", 
    onSelect: function(dateText, inst) { 
     $.ajax({ 
      type: 'POST', 
      url: 'select_time.php', 
      data: {date : dateText}, 
      success: function(resp){ 
       if(false !== resp){ 
        alert(resp); 
       } 
      } 
     }); 
    } 
}); 

然後在select_time.php

<?php 
    if(!empty($_POST['date'])): 
     $mysqli = new mysqli('connection info'); //mysqli connection 
     $stmt= $mysqli->prepare('SELECT reservation.R_time FROM reservation WHERE reservation.R_date = ?'); //prepare the statement 
     $stmt->bind_param('s', $_POST['date']); //bind our parameters 
     $stmt->execute(); //execute our query 
     $stmt->store_result(); // store result so we can check rows 
     $stmt->bind_result($resTime); //we only want the reserveration time 
     $stmt->fetch(); //fetch the rows 
     if($stmt->num_rows() > 0): 
      echo $resTime; //return the time from the database 
      $stmt->close(); //close the statement 
     else: 
      return false; //row doesn't exist, return false 
     endif; 
    endif;  
?> 

這是未經測試,但我看不出有任何理由不應該工作。

-1

我想你混淆兩件事情:

首先,在頁面加載之前,PHP將始終運行(和爲此jQuery),所以在jQuery選擇器上調用PHP將無法工作。

你需要做的是創建一個Ajax功能,將觸發對jQuery的ONSELECT(我一般用OnClose事件,如果它是一個彈出日曆)。

的Javascript:

$("#datepicker").datepicker({ 
minDate: 0, 
showAnim: "bounce", 
onClose: function(dateText, inst) { 
    $.post('select_time.php?dateText=' + dateText, function(queryResult){ 
     // do something with the return query 
    }); 
} 
}); 

PHP頁面:

$connection = mysqli_connect("localhost","username","password","db"); 

$sql = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date={$_post['dateText']}"; 

if ($result = mysqli_query($connection , $sql)) 
    { 
    while ($getData = mysqli_fetch_field($result)) 
     { 
      echo $getData->R_time; 
     } 
    mysqli_free_result($result); 
    } 

mysqli_close($connection); 
+0

非常感謝,我還有一個問題,如果我想從該網頁獲得$時間變量是什麼,是否有需要或只是變量將與日期選擇原來的頁面中定義的任何聲明? – 2013-04-24 18:44:15

+0

請不要使用此答案中提供的MySQL。它已被棄用並充滿缺陷。這是不安全的。相反,使用'MySQLI' – Ohgodwhy 2013-04-24 18:48:42

+0

對不起,我有點困惑你的問題。 PHP頁面上的$ time變量將回顯到javascript頁面,並在響應變量queryResult(在上面的代碼中)中可用。從那裏你可以做你喜歡的事情。 @Ohgodwhy好點。我只是試圖複製/精簡OP爲清晰起見而寫的內容。 – theWizardsBaker 2013-04-24 18:49:34