简体   繁体   中英

jQuery form data not sending to PHP page

I'm very new to anything outside of PHP, so forgive me if this comes off as simple.

I'm trying to create a simple registration form, which then calls a PHP function, which inserts the data.

The problem is, the data doesn't seem to be going to the page.

My form:

<!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>

And then, the PHP:

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

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

Where do_reg() calls the process of registering.

Make the following changes, (follow good practice)

<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>

On php side:

You are writing everything inside a function( register ) and not calling it, instead do something like this,

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

You can't pass a query string in the URL using POST. Add the "type=register" to your data:

$.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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM