简体   繁体   中英

AJAX, PHP form not submitting to database

I've been trying to get this to work for ages, and have read a lot of other answers to similar questions ( How to add AJAX Submit to PHP validation and return message? , ajax submit form why it cannot echo $_POST ) but I just can't seem to get it to work.

Basically what I'm trying to create is a sign-up form that just inserts someone's email address in a new row in a table so I can measure my visitors' conversion rate! Without further ado, here are my scripts, and I sincerely hope you can help me with it :)

HTML Form:

<!-- Signup Form -->
        <form id="signup-form" name="emailform" method="post" action="send_post.php">
            <input type="email" name="email" id="email" placeholder="Email Address" />
            <input type="submit" value="Sign Up" />
        </form> 
<script src="assets/js/main.js"></script>

send_post php:

 <?php
 // Fetching Values From URL
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "email";
$email = $_POST['email'];

//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Insert the data

mysqli_query($conn,"INSERT INTO email (email)
VALUES ('$email')");


$conn->close();
?>

Javascript + AJAX:

//Submitting the form
$('#signup-form').submit(function () {
      $.ajax({type: "POST",
              url: "send_post.php",
              data: $("#signup-form"),
              success: function () {
              alert("success");
     }
});
     e.preventDefault(); 
     return false;
});

For the sake of readability I have only included a small portion of the JS code with the ajax bit in it. PS. When I navigate directly to send_post.php it creates an empty row in the database.

There is plenty wrong here, to name a few:

  • You are not cancelling the default submit event correctly, e is not defined.
  • You are not sending any data, you need to serialize the form and send that, not the form object itself.
  • You have an sql injection problem, you should switch to prepared statements and bound placeholders.

您的数据应采用key:value格式才能正确发布

data: {email:$('#email').val()}

I think it's not sufficient to set the request data to the form object:

data: $("#signup-form"),

You need to set the form values explicitly or serialize the form object. See eg Pass entire form as data in jQuery Ajax function for reference.

Try to update your Form-Javascript:

    $('#signup-form').on('submit', function () {
    ...
    data: { email: $('#email').val() }
    ...

So the $_POST['email'] will reach your PHP-Backend as $_POST['email].

Remove the form to make sure the button doesn't refresh the site, when sending normal POST action:

<input type="email" name="email" id="email" placeholder="Email Address" />
<button id="signUpBtn">Sign up</button>
<script src="assets/js/main.js"></script>

send_post.php:

$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "email";
$email = $_POST['email'];

//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Insert the data

mysqli_query($conn,"INSERT INTO email (email)
VALUES ('$email')");


$conn->close();
?>

Submitting the form:

                        $('#signUpBtn').on("click",function (e) {

                            $.ajax({
                                type: "POST",
                                url: "send_post.php",
                                data: { email: $("#email").val() },
                                success: function () {
                                    alert("success");
                                }
                            });
                            e.preventDefault(); 
                            return false;
                        });

This should do the trick. Make sure to notice the changes I've done in your jQuery part.

There is an answer similar to mine but my php part is much secure so here is the the code.

HTML

<form id="signup-form" name="emailform" >
 <input type="email" name="email" id="email" placeholder="Email Address" />
 <input type="button" id="signup" value="Sign Up" />
</form>

Jquery

$(document).ready(function (){
    $(document).on('click', '#signup', function (){
        $.ajax({
                url: "send_post.php",
                type: "POST",
                data: {
                        "emali": $("#email").val()
                    }
                success: function (response) {
                    alert("response");
                    }
               });
    })
})

PHP

<?php
 // Fetching Values From URL
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "email";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Insert the data
$stmt = $conn -> prepare("INSERT INTO email (email) VALUES (?)");
$stmt -> bind_param('s', $email);

if($stmt -> execute()){
    echo "Done";
}else{
    echo "Not added";
}

$conn->close();
?>

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