数据没有从javascript函数发送到php表单

Data not being sent to a php form from a javascript function

本文关键字:php 表单 函数 javascript 数据      更新时间:2023-09-26

我正在尝试使用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!!";
?>

Ajax是异步的,这意味着它在后台工作,直到工作完成,在Ajax完成之前,您要离开页面导航,使用以下行:

window.location.href = "index.php";

把它放在成功的方法中:

success:function(msg)
{
    alert ("Register Complete");
    window.location.href = "index.php"; 
}