来自PHP的AJAX响应禁用按钮

时间:2014-09-07 01:04:11

标签: javascript php jquery ajax

我已经尝试在Stack Overflow上搜索过去1小时,尝试使用不同的方法而没有工作方法,所以认为它的时间是一个线程。

好的,让我试着解释一下我要做的事情;

1)用户将用户名输入到字段中 2)AJAX发送并检查数据库的用户名 3)如果使用了用户名,js将禁用提交按钮 4)否则,如果不是,js允许他们提交。

我会告诉你我目前的代码! 这是我的js?

        <script type="text/javascript">
        $(document).ready(function () {

    $("#username").blur(function () {
      var username = $(this).val();
      if (username == '') {
        $("#availability").html("");
      }
      else{
        $.ajax({
          url: "class.validation.php?username="+username
        }).done(function( data ) {
          $("#availability").html(data);
          if($.html(data) == 'success') {
                alert('blah')
            }
        });   
      } 
    });
  });
</script>

这是PHP

     $username = $_GET['username'];

$username = strtolower($username);

$stmt = $mysqli->prepare("SELECT username FROM databasename WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$resultSet = $stmt->get_result();

$array = array('name1', 'name2', 'name3', 'name4');

//Prints the result
if (in_array($username, $array) == 1) {
    echo "<img src='https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'>";
    exit();
}elseif (strlen($username) < 3){
    echo 'not enough char';
    echo "<img src='https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'>";
    exit();
}elseif (mysqli_num_rows($resultSet) == 0) {
    echo "<img src='https://cdn1.iconfinder.com/data/icons/ledicons/accept.png'>";
    die();
} else{
    echo "That username has been taken!";
    echo "<img src='https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'>";
    die();
}

我用来显示消息的HTML;

<input type="text" id="email" name="email" class="email_landing" placeholder="Enter your email address">
                        <input type="text" id="username" name="username" class="username_landing" placeholder="Choose your username">
                        <input type="submit" class="submit_landing" id="submit" name="submit" value="Claim">
<div id="availability"></div> 

3 个答案:

答案 0 :(得分:0)

.done()回调中:

.done(function( data ) {
    // Prints the response of your php script
    $('#availability').html(data); 

    // Checks wether to disable the button or not
    if(data == 'That username has been taken!' || data == 'not enough char') {
        $("#submit").attr('disabled', 'disabled');
    } else {
        $("#submit").removeAttr("disabled");
    }
});  

答案 1 :(得分:0)

<强>的JavaScript

$('#username').blur(function() { // typical usage
$('#username').keyup(function() { // or use THIS to check after each keystroke!
    if ($(this).val() === '') {
        $('#loginButton').attr('disabled','disabled');
        $('#availability').attr('src','https://cdn2.iconfinder.com/data/icons/ledicons/cross.png');
        $('#loginMessage').text('Username may not be blank!');
    } else {
        $.getJSON('class.validation.php',{username:username},function(data) {
            $('#availability').attr('src',data.icon);
            $('#loginMessage').text(data.msg);
            if (data.isValid === true) {
                $('#loginButton').removeAttr('disabled');
            } else {
                $('#loginButton').attr('disabled','disabled');
            };
        });
    }
});

<强> PHP

$username = $_GET['username'];
$username = strtolower($username);
$stmt = $mysqli->prepare("SELECT username FROM databasename WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$resultSet = $stmt->get_result();
$array = array('name1', 'name2', 'name3', 'name4');
//Prints the result
if (in_array($username, $array) == 1) {
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'
    $sback['isValid'] = false;
    $sback['msg'] = 'That username is already in use!';
} elseif (strlen($username) < 3){
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'
    $sback['isValid'] = false;
    $sback['msg'] = 'That username is too short!';
} elseif (mysqli_num_rows($resultSet) == 0) {
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/accept.png'
    $sback['isValid'] = true;
    $sback['msg'] = 'That username is available!';
} else {
    $sback['icon'] = 'https://cdn2.iconfinder.com/data/icons/ledicons/cross.png'
    $sback['isValid'] = false;
    $sback['msg'] = 'There was a problem!';
}
echo json_encode($sback,JSON_PRETTY_PRINT);

<强> HTML

<input type="text" id="email" name="email" class="email_landing" placeholder="Enter your email address">
<input type="text" id="username" name="username" class="username_landing" placeholder="Choose your username">
<input type="submit" class="submit_landing" id="loginButton" name="submit" value="Claim">
<div><img id="availability" /></div>
<div id="loginMessage"></div>

答案 2 :(得分:0)

虽然有一个答案可以帮助您解决问题,但我建议使用JSON来定义PHP的错误消息。这样,你就不会在你的PHP上创建html字符串标签,因为它处理数据(确切地说它应该做什么!),使它尽可能地清晰。

你的JS可能是:

$(document).ready(function () {

  $("#username").blur(function () {
    // Adding your field as variable to ease any ID changes
    var username      = $(this).val(),
        divAvailable  = $("#availability");

    // Client-side validation
    if (username.length == 0) {
      divAvailable.html('');
    } else {
      divAvailable.html('');

      // data allows you to send your GET values
      // making URL string clean. It receives an
      // object where index are GET indexes to be
      // handled by PHP, and values are... values!
      // 
      // Datatype will tell to $.ajax callback
      // functions that anything that retuns as a
      // response from the request, is a JSON, so
      // you don't need to $.parseJSON(response).
      $.ajax({
        url: "class.validation.php",
        data: {username : username},
        dataType: 'json'
      }).done(function(data) {
        // Creating default html elements.
        var messageElement = $("<p class='validation-message'></p>"),
            imageElement   = $("<img class='validation-image' src=''>");

          // As data is a JSON, and JSON returns exactly
          // two keys, informing image and a message, you
          // only need to put them as any other string value
          // using jQuery methods.

          // Setting <p> tag html
          messageElement.html(data.message);

          // Setting <img> tag src attribute
          imageElement.attr('src', data.image);

          // Since we already cleaned the $("#availability")
          // element, it's just append both element. You  may
          // change the order as you see fit.
          divAvailable.append(messageElement);
          divAvailable.append(imageElement);

          // I knew data.valid would be useful somewhere!
          // Since valid is a boolean value and there is a
          // jQuery method that allow us to handle HTML element
          // attributes by setting them true or false, you 
          // just need to use the very same data.valid value.
          $('.submit_landing').attr('disabled', !data.valid);
        }
      });   
    } 
  });
});

你的PHP:

$username   = $_GET['username'];
$username   = strtolower($username);

// Adding a new array that will be encoded as JSON
$validation = array('message' => '', 'image' => '', 'valid' => false);

// Database stuff well done with statement.
$stmt = $mysqli->prepare("SELECT username FROM databasename WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$resultSet = $stmt->get_result();

$array = array('name1', 'name2', 'name3', 'name4');

//Prints the result

// To use json_encode function, we must have an array.
// In each case, you only need to change the values already
// setted.

if (in_array($username, $array) == 1) {
    $validation['message'] = "Error Message #1";
    $validation['image']   = "https://cdn2.iconfinder.com/data/icons/ledicons/cross.png";
} elseif (strlen($username) < 3){
    $validation['message'] = "not enough char";
    $validation['image']   = "https://cdn2.iconfinder.com/data/icons/ledicons/cross.png";
} elseif (mysqli_num_rows($resultSet) == 0) {
    $validation['valid']   = true;
    $validation['image']   = "https://cdn1.iconfinder.com/data/icons/ledicons/accept.png";
} else {
    $validation['message'] = "That username has been taken!";
    $validation['image']   = "https://cdn2.iconfinder.com/data/icons/ledicons/cross.png";
}

// I even added a 'valid' key, for, whatever reason you may
// have to only validate the valid key.

// Then echo! it's not return, it's echo json_encode.
echo json_encode($validation);

我甚至会在PHP上添加一些常量来保存图片网址和消息。这样你只能调用常量,而不需要搜索你的图像网址所在的所有代码。

记住,不要重复自己!