[英]Data not being sent to a php form from a javascript function
我正在嘗試使用JavaScript和PHP制作注冊表,但是遇到了問題。 JavaScript代碼不會將數組發送到register_submit.php。 我嘗試研究互聯網上的一些示例以及StackOverflow上的其他帖子,但是沒有一個答案似乎可以解決我自己的問題。
用戶進入registration.php頁面,填寫表單並點擊Submit按鈕,該按鈕調用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!!";
?>
Ajax是異步的,這意味着它在后台運行直到完成工作為止,您正在使用此行完成ajax之前離開頁面:
window.location.href = "index.php";
將其放入成功方法中:
success:function(msg)
{
alert ("Register Complete");
window.location.href = "index.php";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.