我不知道這裏有什麼問題。 preventDefault應該停止提交表單,但仍然繼續。我有一個ajax調用,它驗證用戶是否有效。如果不是,請阻止提交。否則,繼續登錄和主頁。表格仍然提交甚至與preventDefault
表
<form id="signIn" method="post" action="processForms.php">
<table cellspacing="10">
<tr id="errorSignIn" hidden="hidden">
<td class="centerItem errorMessage" colspan="3">
Incorrect Username and/or Password
</td>
</tr>
<tr>
<td><input type="text" id="username" name="username" autocomplete="off" autofocus required placeholder="Username..."></td>
<td><input type="password" id="password" name="password" autocomplete="off" required placeholder="Password..."></td>
<td><input type="submit" name="processButton" class="signIn" value="Sign-in" ></td>
</tr>
</table>
</form>
的Javascript
$('#signIn').submit (function (e) {
var username = $('#username').val();
var password = $('#password').val();
var dataString = "username=" + username + "&password=" + password;
$.ajax({
type: "POST",
url: "ajaxCheck.php",
data: dataString,
cache: false,
success: function (result) {
if (!result) {
$('#errorSignIn').removeAttr('hidden');
e.preventDefault();
return false;
}
}
});
});
ajaxCheck.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5($password);
$dbConnection = mysqli_connect('localhost','root','','onboard');
$query = "SELECT * FROM account WHERE username='$username' AND password='$password'";
$result = mysqli_query($dbConnection,$query);
$count = mysqli_num_rows($result);
if ($count == 1) { echo true; }
else { echo false; }
您只是在內部函數返回false,但外部函數沒有返回值,所以提交將被解僱。 – Tyr 2014-09-24 01:43:38
@Tyr我試着添加「return false;」到另一個函數並向內部函數添加else子句以返回true,但現在當用戶存在時它不會提交表單。 – 2014-09-24 02:02:23
您現在的代碼已打開[** SQL注入**](http://stackoverflow.com/q/60174/)。使用[** CRYPT_BLOWFISH **](http://security.stackexchange.com/q/36471)或PHP 5.5的['password_hash()'](http://www.php.net/manual/en/) function.password-hash.php)函數。對於PHP <5.5,使用['password_hash()兼容包]](https://github.com/ircmaxell/password_compat)。另外,[**使用準備好的語句**](http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php)或[**使用準備好的語句**的PDO](http ://php.net/pdo.prepared-statements)。 – 2014-09-24 02:13:34