weixin_33743703 2017-03-16 12:50 采纳率: 0%
浏览 80

为什么我的Ajax代码无法运行?

I'm just trying to check whether the username already exists, the basic idea is that when the form is sent,my ajax code will connect to checkUsername.php, and checkUsername.php will go to my database and check whether the username is already exists, and return a span.

$.ajax({
      url: "checkUsername.php",
      type: "post",
      data: {"usernameCheck": v1},  
      dataType:"text",
      success:function(data){
    alert("system avaliable!!"); 
    if($("#status-not-available").val(data) == "no"){
        $('#username').css({'border' : '4px solid red'});
        checkUsername = false;
    }
    else{
        $('#username').css({'border' : '4px solid white'});
    }
      },
      fail:function(data){
    alert("system not avaliable");  
      },
  });

php:

$database = new SQLite3('myDatabase.db');  //setup connection
$usernameCheck = $_POST['usernameCheck'];  //get the username they input
$stmt = $database->prepare("SELECT * FROM users WHERE username = :usernameCheck");
$stmt->bindValue(':usernameCheck',$usernameCheck,SQLite3_TEXT);
$row = $stmt->execute()->fetchArray();

if(isset($row['username'])){
    echo "<span class='status-not-available'>no</span>";
}
else{
    echo "<span class='status-not-available'>yes</span>";
}
  • 写回答

2条回答 默认 最新

  • weixin_33699914 2017-03-16 12:55
    关注

    Ajax's dataType:"text" means you want to return response as text.But you are returning html as response also this html is not loaded in DOM so that causes error.

    JS

    $.ajax({
          url: "checkUsername.php",
          type: "post",
          data: {"usernameCheck": v1},  
          dataType:"text",
          success:function(data){
        alert("system avaliable!!"); 
        if(data == "no"){
            $('#username').css({'border' : '4px solid red'});
            checkUsername = false;
        }
        else{
            $('#username').css({'border' : '4px solid white'});
        }
          },
          fail:function(data){
        alert("system not avaliable");  
          },
      });
    

    PHP

    $database = new SQLite3('myDatabase.db');  //setup connection
     $usernameCheck = $_POST['usernameCheck'];  //get the username they input
     $stmt = $database->prepare("SELECT * FROM users WHERE username = :usernameCheck");
     $stmt->bindValue(':usernameCheck',$usernameCheck,SQLite3_TEXT);
     $row = $stmt->execute()->fetchArray();
     if(isset($row['username'])){
     echo "no";//just send response as text rather than html
     }
     else{
    echo "yes";
     }
    
    评论

报告相同问题?