简体   繁体   中英

jquery remote validation is not submitting the form

I cannot get this basic form validation to submit. I read that the remote is the cause. Is there any way to fix it as I need it to check if a username exists before registering a new user?

I am using jQuery Validation Plugin v1.12.0 if it matters

$("#regForm").validate({
   rules: {
        username: {         
            remote: {   
                url: "username_db.php", 
                type: "post"     
            }   
        }
    },
    messages: {
        username: {         
            remote: "Username already in use"
        }
    }
});

PHP:

require_once 'db.php';

if ( $conn = connect() ) {
    $row = $conn->prepare("SELECT * FROM users WHERE username = '".$_REQUEST['username']."'");
    $row->execute();
    $rs = $row->rowCount();

    if($rs > 0){
        echo 'false';
    }else{
        echo 'true';
    }
}   

EDIT:

<form action="" method="post" id="regForm" name="regForm">
    <input type="text" name="username">
    <input type="submit" name="go" value="GO">          
</form>

A few things;

First: You must protect yourself against SQL injection - see for example What is SQL injection?

Second: Your php must output the 'true' or 'false' value, not return it. According to the remote-method documentation, it could also output a json-encoded error message like "The user does not exist"

Third: You can use the error_log() function to debug your PHP code and ensure that it's running - the messages appear in the php log file.

So try this for your PHP code:

require_once 'db.php';

//(Using PDO for db access - see http://php.net/manual/en/book.pdo.php )
if ($pdo = connect() ) { 
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->bindValue(":username", $_REQUEST['username']);
    if ( $stmt->fetchAll() ) 
        echo "true";
    else 
        echo json_encode("User does not exist");
}

Although you have not specified what the exact problem is, you are not sending back any values to the validate plugin.

The plugin expects something that evaluates to valid json and although you have a return statement, you are not actually outputting anything.

The end of your php script should be something like:

if($rs > 0){
    echo json_encode(false);    // returns "false"
}else{
    echo json_encode(true);     // returns "true"
}

Also, the reason you prepare a statement, is to protect yourself from sql injection. You would need a placeholder and bind the value of your variable after preparing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM