douhoujun9304
douhoujun9304
2015-10-23 14:32

使用ajax检查文本输入字段的值

  • php
  • html
  • ajax
  • javascript
  • jquery

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.

This is the HTML form input field

<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>

A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.

This is my Jquery code for this.

$(document).ready(function(){

if ($('#screenName').length > 0){

    var screenName = $("input").keyup(function(){
        var value = $(this).val();
        return value;
    })

    $.ajax({
        type: 'post',
        url:  'screenNameCheck.php',
        data: 'Screen_Name=' + screenName,

        success: function (r) {
            $('.screenNameError').html(r);
        }
    })

}

});

This is the PHP file that gets called to make the DB query

$screenName = $_POST['Screen_Name'];

$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results

$resultCount = intval($numResults);

if($resultCount > 0){
    echo "The username entered already exists. Please a different user name.";
}

For some reason my Jquery is not firing when I type the username in the form :/

Thanks in advance

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答

为你推荐