对于我的生活,我无法获得Ajax请求工作并提交我的HTML表单而不刷新,我从来没有能够拿起Ajax。我希望我的表单运行register.php而不刷新或重定向到另一个页面。理想情况下,我想在div或其他内容中添加“您已注册”的消息但是现在我只希望我的表单无需刷新即可提交。
这是我的HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Social Media</title>
<script src="jquery-3.1.1.min.js"></script>
<script src="register.js"></script>
</head>
<body>
<span id='messasge'></span>
<form id='register_form' method='post' action='register.php'>
First: <input type='text' name='first_name' maxlength='30' required='required'><br>
Last: <input type='text' name='last_name' maxlength='30' required='required'><br>
Email: <input type='text' name='email' maxlength='60' required='required'><br>
Password: <input type='password' name='password' maxlength='60' required='required'><br>
<input type='submit' id='register_user' name='register' value='Register'>
</form>
<br>
<form id='login_form' action='login.php'>
Email: <input type='text' name='email' maxlength='60' required='required'><br>
Password: <input type='password' name='password' maxlength='60' required='required'><br>
<input type='submit' name='login' value='Log In'>
</form>
</body>
</html>
这里发送表单的register.php:
require_once 'connect.php';
// Salt for Hasing Password
$salt = '$kl._';
$pepper = 'l*&s';
// Sanative Input Completely
function sanitizeString($conn, $var) {
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
$var = $conn->real_escape_string($var);
return $var;
}
// Format Name w/ Only Capital First Letter
function formatName($var) {
$var = strtolower($var);
$var = ucwords($var);
return $var;
}
if(isset($_POST['register'])) {
$first_name = sanitizeString($conn, formatName($_POST['first_name']));
$last_name = sanitizeString($conn, formatName($_POST['last_name']));
$email = sanitizeString($conn, $_POST['email']);
$password = hash('ripemd128', $salt . $_POST['password'] . $pepper);
$stmt = $conn->prepare('INSERT INTO users (first_name, last_name, email, password)VALUES(?, ?, ?, ?)');
$stmt->bind_param('ssss', $first_name, $last_name, $email, $password);
$stmt->execute();
$stmt->close();
$conn->close();
}?>
的JavaScript
$('#register_user').click(function() {
$.post( $("#register_form").attr("action"),
$("#register_form :input").serializeArray(), function(info) {
$("#message").html(info);
});
});
$("#register_user").submit(function() { return false; });
答案 0 :(得分:1)
您需要捕获提交事件并返回false。用这个替换你的jQuery:
$(function() {
$('#register_form').submit(function(event) {
event.preventDefault();
$.post( $("#register_form").attr("action"),
$("#register_form :input").serializeArray(), function(info) {
$("#message").html(info);
});
});
});
详细了解preventing default event actions和jQuery AJAX Basics。在进行故障排除时,请确保在浏览器的开发人员工具中观看AJAX请求/响应。
我已经编辑了代码,为jQuery代码添加了一个文档就绪处理程序,因为你在文档的开头加载了jQuery。这实质上使jQuery等待运行,直到整个文档被加载。