[英]Checking and submitting form via Ajax in boostrap modal
我在 boostrap 的模態窗口中有一個登錄表單
<form method="post" id="loginForm" action="index.php">
<label for="email">Email:</label>
<input class="form-control" type="text" name="email" value="" id="emailLogin"/><br/>
<label for="password">Password:</label>
<input class="form-control" type="password" name="password" value="" id="passwordLogin"/><br/>
<div id="loginAlert" class="alert alert-danger" role="alert">Email or password incorrect</div> <!-- Hidden by default -->
<button type="submit" name="login" class="btn btn-primary" id="loginButton">Login</button>
<script src="checkLoginForm.js"></script></form>
我想在提交之前檢查此表格(如果電子郵件和密碼正確)。 如果檢查電子郵件和密碼的函數返回 1,則有錯誤。 在這種情況下不應提交表單,它應該只是使警報可見。 如果一切正確,則應提交。
事情是:如果電子郵件和密碼不正確,我可以阻止表單提交,但如果它們正確,我無法提交。 這是checkLoginForm.js
的代碼
$(document).ready(function() {
$("#loginForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'include/ajax.php?action=checkLogin',
data: {
email: $("#emailLogin").val(),
password: $("#passwordLogin").val(),
},
success: function(result) {
console.log(result);
if(result == 0) {
} else {
$("#loginAlert").css({"display": "block"});
}
}
});
});
});
當結果 == 0 時,我不知道該怎么辦。如果我執行$("loginForm").submit();
,這不會提交表單(其他部分確實有效)。
謝謝您的回復。
我建議您使用簡單的$.post
,這是使用$.ajax
進行 POST 請求的一種簡寫方式。 只需檢查您的 php 文件中提供的值是否正確,如果它們正確處理該數據並返回 true 或將用戶重定向到另一個頁面,否則返回 false。
$(document).ready(function() {
$("#loginButton").on('click', function (e){
e.preventDefault();
var email = $("#emailLogin").val();
var passwd = $("#passwordLogin").val();
$.post('include/ajax.php?action=checkLogin', {email: email, password: passwd}, function (data) {
var res = $.parseJSON(data);
if (res.result == true) {
//you can redirect the or display a message to the user.
//redirect the user to another page
//$("#loginAlert").css({"display": "block"}).html("login successful");
}else {
$("#loginAlert").css({"display": "block"});
}
});
});
});
然后在你的php文件中
if (isset($_GET['action']) && $_GET['action'] == 'checkLogin') {
$passwd = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
//validate inputs here
//get data from db
//then compare values
//if values match return true
//$db_mail and $db_passwd are from the db.
if ($email == $db_mail && $passwd == $db_passwd) {
//if the provided information is correct
//process it here, login the user.
//redirect if necessary.
// or return results to JS
echo json_encode(['result' => true]);
} else {
//if the information is wrong return false to JS
//and alert the user
echo json_encode(['result' => false]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.