我正在尝试使用JavaScript和PHP制作注册表单,但我遇到了问题。 JavaScript代码不会将数组发送到register_submit.php。我已尝试在互联网上查看一些示例以及StackOverflow上的其他帖子,但没有一个答案似乎解决了我自己的问题。
用户进入registration.php页面,填写表单并点击调用checkForms()方法的提交按钮。 setValues()方法将注册表单中的值设置为单个变量。我检查了检索到的变量是否正确(它们是)。
编辑:问题不在于有两个$ password变量。意外测试错误。
JavaScript代码:
function checkForms() {
setValues();
callPHP();
}
function callPHP() {
alert(registration.emailR);
// call ajax
$.ajax({
type: "POST",
url: 'register_submit.php',
data:{name:registration.usernameR, email:registration.emailR, password:registration.password1R, forename:registration.forenameR, surname:registration.surnameR, country:registration.countryR, dob:registration.dobR},
success:function(msg) {
alert("Register Complete");
}
});
// Go to homepage
window.location.href = "index.php";
}
PHP代码:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$country = $_POST['country'];
$dob = $_POST['dob'];
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$con = new mysqli($host, $user, $password, $database);
if(!$con)
die('Connection failed'.mysql_error());
else echo "Connection successful ";
mysqli_select_db($con, $database);
$query = "INSERT INTO user (userID, username, dob, email, password, isAuthor, isAdmin, country, surname, firstname) VALUES ('user001', '$username', '$dob', '$email', '$password', '0', '0', '$country', '$surname', '$forename')";
echo $query;
mysqli_query($con, $query);
echo "Registration Complete!!";
?>
答案 0 :(得分:3)
Ajax是异步的,这意味着它在后台运行,直到作业完成,你在ajax完成此行之前离开页面:
window.location.href = "index.php";
将其置于成功方法内:
success:function(msg)
{
alert ("Register Complete");
window.location.href = "index.php";
}