试图通过ajax将数据发送到php

时间:2014-08-04 12:54:02

标签: php jquery ajax

所以我试图创建一些代码来检查用户名是否被占用。我有一半在那里遇到麻烦。我是新手,并试图学习如何做到这一点&代码会很乱。

jquery:

$('#signusername').keyup(function()
        {       
        var username=$('#signusername').val();         
        if(username != ''){

            $.post('username_check.php', {signusername :username}, function(result)

            {
                    if(result==''){
                        $('.error').text('Avaliable');
                        } else{
                        $('.error').text('Taken');
            }
            }
            );
        }else{
        $('.error').text('???');//this is the the only thing that outputs correctly

        }

php:

function checkUsername($signusername, $conn) {
            $stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
                $stmt->bindParam(1, $signusername);
                $stmt->execute();
                if($stmt->rowCount() == 1) {
                   return TRUE;
                }
                };


if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
    $signusername= $_POST['signusername'];
    checkUsername($signusername, $conn);
    $result='';
    if(checkUsername($signusername, $conn) == TRUE){
    $result='';
    }else{
    $result='';
}
echo $result;
};

我使用相同的代码检查在提交表单时是否使用了用户名,因此我不认为这是问题所在。我假设我在移动用户名变量时做错了什么?希望你能帮忙。

2 个答案:

答案 0 :(得分:1)

};

之后检查您的控制台是否有syntex错误}删除分号

同时删除两次调用函数并在两种情况下都将结果发送空白,以便在失败条件下将一些响应发送回ajax

if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
    $signusername= $_POST['signusername'];
    $result='';
    if(checkUsername($signusername, $conn) == TRUE){
    $result='user found';  
    }else{
    $result='user not found';
    }
   echo $result;
}

答案 1 :(得分:1)

试试此代码

function checkUsername($signusername, $conn) {
            $stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
               $stmt->bindParam(1, $signusername);
                $stmt->execute();
                if($stmt->rowCount() == 1) {
                   return TRUE;
                }
return false;
                };


if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
    $signusername= $_POST['signusername'];
    $result = checkUsername($signusername, $conn);
    if($result != TRUE){
       $result='';
    }else{
}
echo $result;
};