简体   繁体   English

AJAX,PHP表单未提交到数据库

[英]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. 我一直在尝试使它工作多年,并且已经阅读了许多其他类似问题的答案( 如何添加AJAX提交到PHP验证并返回消息?ajax提交表单为什么它不能回显$ _POST ),但是我只是似乎无法使其正常工作。

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: HTML表单:

<!-- 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: 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: 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. 为了便于阅读,我只包含了JS代码的一小部分,其中包含了ajax位。 PS. PS。 When I navigate directly to send_post.php it creates an empty row in the database. 当我直接导航到send_post.php时,它将在数据库中创建一个空行。

There is plenty wrong here, to name a few: 这里有很多错误,仅举几例:

  • You are not cancelling the default submit event correctly, e is not defined. 您没有正确取消默认的提交事件,未定义e
  • 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. 您有SQL注入问题,应切换到准备好的语句和绑定的占位符。

您的数据应采用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. 请参见例如在jQuery Ajax函数中将整个表单作为数据传递以供参考。

Try to update your Form-Javascript: 尝试更新您的Form-Javascript:

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

So the $_POST['email'] will reach your PHP-Backend as $_POST['email]. 因此,$ _ POST ['email']将以$ _POST ['email]的形式到达您的PHP后端。

Remove the form to make sure the button doesn't refresh the site, when sending normal POST action: 发送正常的POST操作时,请删除表单以确保按钮不会刷新站点:

<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: 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. 确保注意我在jQuery部分所做的更改。

There is an answer similar to mine but my php part is much secure so here is the the code. 有一个类似于我的答案,但是我的php部分很安全,所以这里是代码。

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

<?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();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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