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.