PHP JavaScript Bootstrap - 使用AJAX在表单字段上成功/错误

时间:2017-01-14 22:12:11

标签: javascript php ajax

我的表单中有一个字段,其中包含一个授权代码'并使用AJAX和PHP对数据库进行检查。目前,如果授权代码有效,它将显示勾号,如果错误则显示交叉。我想反过来使用表单上的Bootstrap反馈,如果代码错误则反馈给用户。我有验证代码,到目前为止只使用此Bootstrap方法检查提交时字段是否为空。如果授权代码错误,我该如何扩展它以便产生红色轮廓和交叉,反之亦然?提前感谢您的帮助。

form.html:

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home</title>
    <!-- Scripts -->
    <script src="js/jquery-3.1.1.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/validator.js"></script>
    <script src="js/validator.min.js"></script>
    <!-- CSS -->
    <link href="css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="css/bootstrap.css" rel="stylesheet">
</head>

<body>

<form id="auth_form" action="action.php" method="post">

  <div class="form-group has-feedback" name="auth_code" id="auth_code">
    <label for="auth_code" class="control-label">
    Authorisation Code</label>
    <input class="form-control" id="auth_code_input" name="auth_code_input" type="password">
    <span class="form-control-feedback glyphicon" id="iconBad"></span>
      <span id="auth_code_result"></span>
  </div>

  <div class="form-group">
    <div>
      <button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button>
    </div>
  </div>

</form>

<!-- AJAX -->
<script type="text/javascript">
$(document).ready(function() {
    var x_timer;    
    $("#auth_code_input").keyup(function (e){
        clearTimeout(x_timer);
        var auth_code = $(this).val();
        x_timer = setTimeout(function(){
            check_auth_code_ajax(auth_code);
        }, 1000);
    }); 

function check_auth_code_ajax(auth_code){
    var $auth_code = $('#auth_code');
    $("#auth_code_result").html('<img src="img/ajax-loader.gif"/>');
    $.post('auth_code_checker.php', 
        {'auth_code_input':auth_code}, 
        function(data) {
            // data will be JSON, including a status we can use
            $("#auth_code_result").html('');
            showStatus(data.status, $auth_code);
        },
        'json'  // Expect JSON response from server
    );
}
</script>

<!-- Validating input -->
<script>
$(document).ready(function() {

   $('#auth_code_input').blur(function(){
      if(!ValidateInput()){
          e.preventDefault();
      }
   });

   $('#auth_form').on('submit', function(e) {
     if(!ValidateInput()){
          e.preventDefault();
      }
   })
 });

function ValidateInput(){
    var $auth_code = $('#auth_code');

    if ($auth_code.val() === "") {
        showStatus('fail', $auth_code)
        return false;
    } else {
        showStatus('ok', $auth_code)
        return true;
    } 
}

 function showStatus(status, $target) {
    if (status === 'ok') {
        $target.removeClass('has-error').addClass('has-success');
        $('.glyphicon', $target).removeClass('glyphicon-remove').addClass('glyphicon-ok');
    } else {
        $target.removeClass('has-success').addClass('has-error');
        $('.glyphicon', $target).removeClass('glyphicon-ok').addClass('glyphicon-remove');
    }
}
 </script>

</body>
</html>

auth_code_checker.php:

<?php

include 'pdo_config.php';
try {
$conn = new PDO($dsn, $user, $pass, $opt);

$auth_code = $_POST["auth_code_input"];  
$stmt = $conn->prepare("SELECT * FROM tbl_instructors WHERE auth_code = :auth_code");
$stmt->bindParam(':auth_code', $auth_code);
$stmt->execute();

$exists = $stmt->fetchColumn();

if ($exists > 0) {
    $response['status'] = 'ok';
} else {
    $response['status'] = 'fail'; 
}

header("Content-Type: application/json", true);
echo json_encode($response);

catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}

$conn = null;

1 个答案:

答案 0 :(得分:1)

最简单的方法是简单地重复使用您在前端验证过程中所做的相同样式。为此,将其解压缩为一个独立的函数,以便您可以从任何地方调用它:

// Apply styles to target element based on status.  Note it expects an element
// with class .glyphicon as a child of the target, as your code has
function showStatus(status, $target) {
    if (status === 'ok') {
        $target.removeClass('has-error').addClass('has-success');
        $('.glyphicon', $target).removeClass('glyphicon-remove').addClass('glyphicon-ok');
    } else {
        $target.removeClass('has-success').addClass('has-error');
        $('.glyphicon', $target).removeClass('glyphicon-ok').addClass('glyphicon-remove');
    }
}

现在您可以更新前端验证以使用它:

function ValidateInput(){
    var $auth_code = $('#auth_code'),
        $input = $('input', $auth_code);

    if ($input.val() === "") {
        showStatus('fail', $auth_code)
        return false;
    } else {
        showStatus('ok', $auth_code)
        return true;
    } 
}

如果您更新PHP以返回某种成功/失败状态而不是图像或HTML,那么您也可以使用相同的代码获取AJAX代码。所以你的PHP可能看起来像:

// ... your existing PHP code
if ($exists > 0) {
    $response['status'] = 'ok';
} else {
    $response['status'] = 'fail'; 
}

header("Content-Type: application/json", true);
echo json_encode($response);

最后更新你的AJAX例程以期待状态响应,并像前端验证一样调用showStatus()

function check_auth_code_ajax(auth_code){
    var $auth_code = $('#auth_code');
    $("#auth_code_result").html('<img src="img/ajax-loader.gif"/>');
    $.post('auth_code_checker.php', 
        {'auth_code_input':auth_code}, 
        function(data) {
            // data will be JSON, including a status we can use
            $("#auth_code_result").html('');
            showStatus(data.status, $auth_code);
        },
        'json'  // Expect JSON response from server
    );
}