如何在下拉菜单中立即更新更新数据

时间:2012-11-15 01:48:41

标签: php jquery ajax mysqli

我有一个应用程序,您可以点击此链接application

查看该应用程序

当您打开该应用程序时,请按照以下步骤操作:

  1. 当您打开应用程序时,您会看到2个下拉菜单,一个用于课程,一个用于模块,请在相关的下拉菜单中选择课程INFO101 - ...和模块CHI2513 - ...,然后单击在“提交课程和模块”按钮上。

  2. 您将看到下面显示的一些细节。您将看到为评估显示的另一个下拉菜单,请从下拉菜单中选择任何评估,您将看到所选评估的详细信息显示在下面的文本输入中,“新日期”和“新开始时间”除外。 / p>

  3. 请点击日历和时钟图标,为相关文字输入选择“新日期”和“新开始时间”。完成后,单击下面的“更新日期/开始时间”按钮。

  4. 将出现一个确认框,单击“确定”。现在,将在下面显示一条消息,说明更新成功,但这是问题所在。如果您查看评估的下拉菜单,您可以看到您刚刚更改的评估,它没有显示新的时间和日期,它仍然显示旧的。现在,如果您刷新页面并按照步骤1和2进行操作,则会在下拉菜单中显示更新时间和日期。

  5. 那么我的问题是,如何在用户确认更新发生后直接在所选评估的下拉菜单中显示新的日期和时间,以便他们可以看到更改已发生在没有需要刷新的情况下?

    当前日期和开始时间文本输入也需要更改以显示更新后的新日期和开始时间,并且新日期和新开始时间文本输入应该返回空白。

    以下是editsessionadmin.php页面,其中显示了应用程序:

    <script type="text/javascript">
    
    function submitform() {    
    
    $.ajax({
    type: "POST",
    url: "updatedatetime.php",
    data: $('#updateForm').serialize(),
    success: function(html){
    $("#targetdiv").html(html);
    }
    });        
    }
    
    function showConfirm(){
    
    var examInput = document.getElementById('newAssessment').value;
    var dateInput = document.getElementById('newDate').value;
    var timeInput = document.getElementById('newTime').value;
    
    if (editvalidation()) {
    
    var confirmMsg=confirm("Are you sure you want to update the following:" + "\n" + "Exam: " + examInput +  "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);
    
    if (confirmMsg==true)
    {
    submitform();   
    }
    }
    } 
    
    $('body').on('click', '#updateSubmit', showConfirm); 
    
    
    
    </script>   
    
    <style>
    .red{ color:red; }
    .green{ color:green; }
    </style>
    
    <?php
    
    // connect to the database
    include('connect.php');
    include('noscript.php');
    
    /* check connection */
    if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
    }
    
    $newassessment = (isset($_POST['Assessmentnew'])) ? $_POST['Assessmentnew'] : '';
    
    $sql = "SELECT CourseId, CourseName FROM Course ORDER BY CourseId"; 
    
    $sqlstmt=$mysqli->prepare($sql);
    
    $sqlstmt->execute(); 
    
    $sqlstmt->bind_result($dbCourseId, $dbCourseName);
    
    $courses = array(); // easier if you don't use generic names for data 
    
    $courseHTML = "";  
    $courseHTML .= '<select name="courses" id="coursesDrop" onchange="getModules();">'.PHP_EOL; 
    $courseHTML .= '<option value="">Please Select</option>'.PHP_EOL;  
    
    while($sqlstmt->fetch()) 
    { 
    $course = $dbCourseId;
    $coursename = $dbCourseName; 
    $courseHTML .= "<option value='".$course."'>" . $course . " - " . $coursename . "</option>".PHP_EOL;  
    
    $outputcourse = ""; 
    $outputcourse .= "<p><strong>Course:</strong> " . $course .  " - "  . $coursename . "</p>";
    
    } 
    
    $courseHTML .= '</select>'; 
    
    $moduleHTML = "";  
    $moduleHTML .= '<select name="modules" id="modulesDrop">'.PHP_EOL; 
    $moduleHTML .= '<option value="">Please Select</option>'.PHP_EOL;  
    $moduleHTML .= '</select>'; 
    
    
    ?>
    
    <script type="text/javascript">
    
    function getModules() { 
    var course = jQuery("#coursesDrop").val(); 
    jQuery('#modulesDrop').empty(); 
    jQuery('#modulesDrop').html('<option value="">Please Select</option>'); 
    jQuery.ajax({ 
    type: "post", 
    url:  "module.php", 
    data: { course:course }, 
    success: function(response){ 
    jQuery('#modulesDrop').append(response); 
    } 
    }); 
    
    
    }
    
    
    </script> 
    
    <h1>EDIT AN ASSESSMENT'S DATE/START TIME</h1>   
    
    <p>You can edit assessment's Date and Start time on this page. Only active assessments can be editted.</p>
    
    <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validation();">
    <table>
    <tr>
    <th>Course: <?php echo $courseHTML; ?></th>
    <th>Module: <?php echo $moduleHTML; ?></th>
    </tr>
    </table>
    <p><input id="moduleSubmit" type="submit" value="Submit Course and Module" name="moduleSubmit" /></p>
    <div id="moduleAlert"></div>
    </form>
    
    <?php
    
    if (isset($_POST['moduleSubmit'])) {    
    
    $outputmodule = ""; 
    
    $moduleInfo = explode("_", $_POST['modules']);
    $moduleId = $moduleInfo[0];
    $moduleName = $moduleInfo[1];
    $outputmodule = sprintf("<p><strong>Module:</strong> %s - %s</p>", $moduleId, $moduleName);
    
    echo $outputcourse;
    echo $outputmodule;
    
    $sessionquery = "
    SELECT SessionId, SessionName, SessionDate, SessionTime, ModuleId
    FROM Session
    WHERE
    (ModuleId = ?)
    ORDER BY SessionName 
    ";
    
    $sessionqrystmt=$mysqli->prepare($sessionquery);
    // You only need to call bind_param once
    $sessionqrystmt->bind_param("s",$moduleId);
    // get result and assign variables (prefix with db)
    
    $sessionqrystmt->execute(); 
    
    $sessionqrystmt->bind_result($dbSessionId,$dbSessionName,$dbSessionDate,$dbSessionTime, $dbModuleId);
    
    $sessionqrystmt->store_result();
    
    $sessionnum = $sessionqrystmt->num_rows();   
    
    if($sessionnum ==0){
    echo "<p>Sorry, You have No Assessments under this Module</p>";
    } else { 
    
    $sessionHTML = '<select name="session" id="sessionsDrop">'.PHP_EOL;
    $sessionHTML .= '<option value="">Please Select</option>'.PHP_EOL;           
    
    while ( $sessionqrystmt->fetch() ) {
    if(time() > strtotime($dbSessionDate." ".$dbSessionTime)){
    $class = 'green';
    } else {
    $class = 'red';
    }
    $sessionHTML .= sprintf("<option value='%s' style='color: %s'>%s - %s - %s</option>", $dbSessionId, $class, $dbSessionName, date("d-m-Y",strtotime($dbSessionDate)), date("H:i",strtotime($dbSessionTime))) . PHP_EOL;  
    }
    
    
    $sessionHTML .= '</select>';
    
    
    $assessmentform = "<form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post'>
    <p><strong>Assessments:</strong> {$sessionHTML} </p>   
    </form>";
    
    echo $assessmentform;
    
    }
    
    
    
    $editsession = "<form id='updateForm'>
    
    <p><strong>Current Assessment's Date/Start Time:</strong></p>
    <table>
    <tr>
    <th>Assessment:</th>
    <td><input type='text' id='currentAssessment' name='Assessmentcurrent' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Date:</th>
    <td><input type='text' id='currentDate' name='Datecurrent' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Start Time:</th>
    <td><input type='text' id='currentTime' name='Timecurrent' readonly='readonly' value=''/> </td>
    </tr>
    </table>
    <div id='currentAlert'></div>
    
    <p><strong>New Assessment's Date/Start Time:</strong></p>
    <table>
    <tr>
    <th>Assessment:</th>
    <td><input type='text' id='newAssessment' name='Assessmentnew' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Date:</th> 
    <td><input type='text' id='newDate' name='Datenew' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Start Time:</th> 
    <td><input type='text' id='newTime' name='Timenew' readonly='readonly' value=''/><span class='timepicker_button_trigger'><img src='Images/clock.gif' alt='Choose Time' /></span> </td>
    </tr>
    </table>
    <div id='datetimeAlert'></div>
    
    </form>
    
    <button id='updateSubmit'>Update Date/Start Time</button>
    
    <div id="targetdiv"></div>
    ";
    
    echo $editsession;
    
    
    }
    
    ?>
    

    下面是ajax调用的updatedatetime.php,用于执行更新并显示成功/错误消息:

    <?php
    
     // connect to the database
     include('connect.php');
    
      /* check connection */
      if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        die();
      }
    
    $sessionname = (isset($_POST['Assessmentnew'])) ? $_POST['Assessmentnew'] : ''; 
    $sessiondate = (isset($_POST['Datenew'])) ? $_POST['Datenew'] : ''; 
    $sessiontime = (isset($_POST['Timenew'])) ? $_POST['Timenew'] : ''; 
    
    $formatdate = date("Y-m-d",strtotime($sessiondate));
    $formattime = date("H:i:s",strtotime($sessiontime));
    
    $updatesql = "UPDATE Session SET SessionDate = ?, SessionTime = ? WHERE SessionName = ?";                                           
    $update = $mysqli->prepare($updatesql);
    $update->bind_param("sss", $formatdate, $formattime, $sessionname);
    $update->execute();
    
    $query = "SELECT SessionName, SessionDate, SessionTime FROM Session WHERE SessionName = ?";
    // prepare query
    $stmt=$mysqli->prepare($query);
    // You only need to call bind_param once
    $stmt->bind_param("s", $sessionname);
    // execute query
    $stmt->execute(); 
    // get result and assign variables (prefix with db)
    $stmt->bind_result($dbSessionName, $dbSessionDate, $dbSessionTime);
    //get number of rows
    $stmt->store_result();
    $numrows = $stmt->num_rows();
    
    if ($numrows == 1){
    
    echo "<span style='color: green'>Your Assessment's new Date and Time have been updated</span>";
    
    }else{
    
    echo "<span style='color: red'>An error has occured, your Assessment's new Date and Time have not been updated</span>";
    
    }
    
            ?>
    

1 个答案:

答案 0 :(得分:1)

以下Javascript应该做你想要的。这应该从您的AJAX代码的成功函数调用。

//Get and store the new date and time.
var newDate = jQuery("#newDate").val();
var newTime = jQuery("#newTime").val();

//Set your current date and time to your new date and time.
jQuery("#currentDate").val(newDate);
jQuery("#currentTime").val(newTime);

//Find the currently selected session and update it.
var selectedOption = jQuery("#sessionsDrop option:selected");
var label = selectedOption.text().split(" - ");
selectedOption.text(label[0] + " - " + newDate + " - " + newTime);

//Clear the new date and time fields.
jQuery("#newDate").val("");
jQuery("#newTime").val("");