0

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.

A. Hartman
  • 83
  • 1
  • 2
  • 8

6 Answers6

1

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.
jeroen
  • 91,079
  • 21
  • 114
  • 132
0

Your data should be in key:value format to be posted right

data: {email:$('#email').val()}
Haziq Ahmed
  • 87
  • 1
  • 6
0

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 e.g. Pass entire form as data in jQuery Ajax function for reference.

Dr. Dreave
  • 539
  • 5
  • 13
0

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

Superpupsi
  • 87
  • 1
  • 8
0

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.

MadsBinger
  • 53
  • 8
  • I don't think removing the form tag is the right approach. Preventing the form from submitting is easily done by using event.preventDefault. Removing the form tags also eliminates typical behaviour, expected by the user, like submitting the form by pressing enter. – Dr. Dreave Oct 17 '17 at 09:28
0

There is an answer similar to mine but my phppart 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();
?>
S4NDM4N
  • 904
  • 2
  • 11
  • 26