2015-04-17 39 views
1

我想知道是否有可能添加一些東西到我的JavaScript,這將允許刷新,如果表單提交正常但不會刷新頁面,如果錯誤返回來自PHP。JavaScript - 停止刷新,如果從PHP返回錯誤

這是可能的嗎?如果有的話,任何人都可以向我提供任何指導,以幫助我實現這一目標。當提交表單並返回消息時,我已設法刷新javascript。

這是JS:

function addCall() { 
    var data = $('#addForm').serialize(); 
    $.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){ 

    $("#addForm").html(response); 
    //'soft'reload parent page, after a delay to show message 
    setTimeout(function(){ 
     $('#addModal').modal('hide') 
     location.reload(); 
    },3500); 

    }).fail(function(jqXHR, textStatus) { 
    alert("Request failed: " + textStatus); 
    }); 
} 

以及處理形式,並驗證它的PHP:

<?php 

session_start(); 

if (empty($_POST['course_title'])) { 
    $message = " Value is required"; 
} 

else { 

    $course_title   = trim($_POST['course_title']); 

    # Validate Course # 

    if (!ctype_alpha($course_title)) { 

     $message = '<p class="error">Course title should be alpha characters only.</p>'; 
    } 

    elseif (strlen($course_title) < 3 OR strlen($course_title) > 50) { 
     $message = '<p class="error">Course title should be within 3-50 characters long.</p>'; 
    } 

    else { 

     include "../includes/db_conx.php"; 

     try 
     { 
      $db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
      $db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

      $sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`) VALUES (:course_title)"); 
      $sql->bindParam(':course_title', $course_title, PDO::PARAM_STR); 
      $sql->execute(); 

      $message = "<p class='text-success'> Record Successfully Added <span class='glyphicon glyphicon-ok'/></p>"; 
     } 
     catch(Exception $e) { 

      if($e->getCode() == 23000) 
      { 
       $message = 'Course already exists in database'; 
      } 
      else 
      { 
       $message = $e->getMessage(); 
      } 
     } 
    } 
} 
die($message); 
?> 

這將真正對用戶有用的,以便能夠做出修訂形式而不是重新寫一遍。

形式:

   <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true"> 
        <div class="modal-dialog"> 
         <div class="modal-content"> 
          <div class="modal-header"> 
           <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
           <h4 class="modal-title">Add New Record: </h4> 
          </div> 
          <div class="modal-body"> 
           <form id="addForm" class="addForm"> 
            <div class="form-group"> 

             <label class="control-label" for="forename">Forename:</label> 
             <div class="controls"> 
              <input id="forename" name="forename" type="text" placeholder="Enter forename(s)" class="form-control" maxlength="100" required=""> 

             </div> 
            </div> 
            <div class="form-group"> 
             <label class="control-label" for="surname">Surname:</label> 
             <div class="controls"> 
              <input id="surname" name="surname" type="text" placeholder="Enter surname" class="form-control" maxlength="100" required=""> 

             </div> 
            </div> 

            <!-- Text input--> 
            <div class="form-group"> 
             <label class="control-label" for="email">Email:</label> 
             <div class="controls"> 
              <input id="email" name="email" type="email" placeholder="Enter a valid email" class="form-control" maxlength="255" value="" required=""> 

             </div> 
            </div> 


            <div class="form-group"> 

             <label class="control-label" for="username">Username:</label> 
             <div class="controls"> 
              <input id="username" name="username" type="text" placeholder="username" class="form-control" value="" maxlength="50" required=""> 

             </div> 

            </div> 
            <div class="form-group"> 

             <label class="control-label" for="password">Password:</label> 
             <div class="controls"> 
              <input id="password" name="password" type="password" placeholder="password" class="form-control" maxlength="40" required=""> 

             </div> 

            </div> 

            <div class="form-group"> 

             <label class="control-label" for="confirm_password">Confirm Password:</label> 
             <div class="controls"> 
              <input id="confirm_password" name="confirm_password" type="password" placeholder="retype password" class="form-control" maxlength="40" required=""> 

             </div> 

            </div> 

            <?php 

            include "../includes/db_conx.php"; 

            try { 

             $db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 

             $db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
             $stmt2 = $db_conx->prepare('SELECT * FROM role_type'); 
             $stmt2->execute(); 
             $roles = $stmt2->fetchAll(PDO::FETCH_ASSOC); 
            } 

            catch(Exception $e) 
            { 
             die ("Could not connect to the database $mysql_dbname :" . $e->getMessage()); 
            } 
            ?> 

            <div class="control-group"> 
             <label class="control-label" for="role_type">Select User Type:</label><p></p> 
             <select name="role"> 
              <option value=''>Select One</option>"; 
              <?php foreach($roles as $role): ?> 
              <option value="<?php echo $role['role_type_code'] ?>"><?php echo $role['role_title'] ?></option> 
             <?php endforeach ?> 
            </select> 
           </div> 
           <p></p> 

           <?php 

            include "../includes/db_conx.php"; 

            try { 

             $db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 

             $db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
             $stmt3 = $db_conx->prepare('SELECT * FROM course_details ORDER BY course_title'); 
             $stmt3->execute(); 
             $courses = $stmt3->fetchAll(PDO::FETCH_ASSOC); 
            } 

            catch(Exception $e) 
            { 
             die ("Could not connect to the database $mysql_dbname :" . $e->getMessage()); 
            } 
            ?> 

            <div class="control-group"> 
             <label class="control-label" for="course_details">Select Course:</label><p></p> 
             <select name="course"> 
              <option value=''>Select One</option>"; 
              <?php foreach($courses as $course): ?> 
              <option value="<?php echo $course['course_code'] ?>"><?php echo $course['course_title'] ?></option> 
             <?php endforeach ?> 
            </select> 
           </div> 
           <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /> 
          </form> 
          </div> 
          <div class="modal-footer"> 
           <div class="btn-toolbar"> 
            <button type="button" class="btn btn-default" class="pull-right" data-dismiss="modal">Close</button> 

            <button type="button" class="btn btn-success" class="pull-right" onclick="addUCall();">Submit <span class="glyphicon glyphicon-saved"></button> 
           </div> 
          </div> 
         </div> 
        </div> 
       </div> 

預先感謝您。

+0

嗯..自從我上次使用PHP已經很長時間了。不過,我認爲你可以從PHP返回提交的數據,並在你的js回調中檢查它是否返回成功。對 ? –

回答

1

您的消息變量包含錯誤和成功消息。它每次收到響應時都會重新加載頁面。
$(「#addForm」)。html(response); -

var n = response.search("class=\'text-success\'"); 
if(n!=-1){ 
     //reload success 
} 
else{ 
    //stay on page, errors 
} 
+0

謝謝,我會給這個去! – user610

+0

這個工程很好,但是我剛剛意識到窗體顯示的模式仍然會在點擊提交時刪除所有表單域。我已將模態形式附加到原始問題上。你知道我可以如何將響應放入表單中,而不是刪除表單輸入請 – user610

+1

寫這個'$(「#addForm」).prepend(response);'而不是'$(「#addForm」)。html (迴應);' – mohit

1

當您在響應中返回錯誤消息時,請檢查錯誤類並在必要時執行重新加載。

$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){ 

     if(response.contains("text-success")) { 
      // put your logic here for success 
     } else { 
      // logic for errors 
     } 
    }); 
+0

謝謝,我會放棄這一切! – user610