jQuery表单数据不发送到PHP页面

时间:2013-12-11 00:07:35

标签: javascript php jquery

我对PHP之外的任何事情都很陌生,所以请原谅我,如果这很简单的话。

我正在尝试创建一个简单的注册表单,然后调用PHP函数来插入数据。

问题是,数据似乎没有进入页面。

我的表格:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
$('#register').on('submit', function (e) {
    $.ajax({
        type: 'POST',
        url: 'http://warofman.com/actions.php?type=register',
        data: $('#register').serialize(),
        success: function () {
            alert('Form was submitted.');
            console.log(e);
        }
        });
    e.preventDefault();
    });
});
</script>
</head>
<body>
    <form id="register">
        Username: <input type="text" name="login"><br>
        Email: <input type="text" name="email"><br>
        Password: <input type="password" name="password"><br>
        Confirm Password: <input type="password" name="confpass"><br>
        <input type="submit" name="submit" value="Register">
    </form>
</body>
</html>

然后,PHP:

function register()
{
    $login = $_POST['login'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confpass = $_POST['confpass'];

    do_reg($login, $email, $password, $confpass);
}

do_reg()调用注册过程。

2 个答案:

答案 0 :(得分:1)

进行以下更改,(遵循良好做法)

<form id="register" action="" method="post">
        <label for="login">Username:</label>
        <input id="login" type="text" name="login"><br>

        <label for="email">Email:</label>
        <input type="email" name="email" id="email" /><br>

        <label for="password">Password:</label> 
        <input type="password" name="password" id="password"><br>

        <label for="confpass">Confirm Password:</label>
        <input type="password" name="confpass" id="confpass"><br>

        <input type="submit" name="submit" value="Register">
    </form>

在php方面:

您正在函数内部编写所有内容(register)而不是调用它,而是执行类似的操作,

if(isset($_POST['submit'])){
  $login = $_POST['login'];
  $email = $_POST['email'];
  $password = $_POST['password'];
  $confpass = $_POST['confpass'];
  do_reg($login, $email, $password, $confpass);
}

答案 1 :(得分:0)

您无法使用POST在URL中传递查询字符串。将“type = register”添加到您的数据中:

$.ajax({
    type: 'POST',
    url: 'http://warofman.com/actions.php',
    data: "type=register&" + $('#register').serialize(),
    success: function () {
        alert('Form was submitted.');
        console.log(e);
    }
    });
e.preventDefault();
});