Ajax 插入数据脚本无法正常工作。我该如何改进这段代码?

Ajax insert data script not working correctly. How can i improve this code?

我创建了一个包含 Bootstrap 模态按钮的页面。当用户单击此按钮时,模式 window 打开并显示一个表单以通过 Ajax 和 PHP 代码在 Mysql table 上插入数据。发生的事情是我的 Ajax 脚本无法正常工作。我试图找到类似的问题,但没有找到解决方案:

  1. Why is code in AJAX success call is not working?
  2. How to insert into mysql table using ajax?

我的 table 有 3 列:

ID   --> INT(11) AI
name --> VARCHAR(100)
email--> VARCHAR(100)

下面是我用来通过 Ajax 脚本添加数据的模态代码:

<button type="button" class="btn btn-block btn-primary" data-toggle="modal" data-target="#dataModal>ADD USER</button>

<!-- Modal -->
<div class="modal fade" id="dataModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" >Add Users</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
         </div>
         <div class="modal-body">
            <form id="usersForm" method="post">
               <input type="text" name="name"/>
               <input type="email" name="email"/>
         </div>
         <div class="modal-footer">
         <button type="button" class="btn btn-secondary" data-dismiss="modal">CLOSE</button>
         <button type="submit" class="btn btn-success" id="submit" >ADD USER</button>
             </form>    
         </div>
      </div>
   </div>
</div>

要通过 PHP 脚本 (insert.php) 将数据发送到数据库,我在我的项目中使用这个 Ajax 脚本代码:

<!--AJAX-->   

<script type="text/javascript">
$(document).on('submit','#usersForm',function(e) {
var Name = $("#name").val();
var Email = $("#email").val();

// AJAX code to send data to php file.
    $.ajax({
        type: "POST",
        url: "insert.php",
        data: {Name:name, Email:email},
        dataType: "JSON",
        success: function(data) {
         alert("Data Inserted Successfully.");
        },
        error: function(err) {
        alert(err);
        }
    });

 }

</script>

下面是我用来在 Mysql table:

上插入数据的 insert.php 代码
<?php

include('db_connect.php');

$Name = $_POST['name'];
$Email = $_POST['email'];

$stmt = $connection->prepare("INSERT INTO users (name, email) VALUES(:name, :email)");

 $stmt->bindparam(':name', $Name);
 $stmt->bindparam(':email', $Email);
 if($stmt->execute())
 {
  $res="Data Inserted Successfully:";
  echo json_encode($res);
  }
  else {
  $error="Not Inserted,Some Probelm occur.";
  echo json_encode($error);
  }

  ?>

还有我的PHP数据库连接脚本db_connect.php

<?php

$username = 'root';
$password = '';
$connection = new PDO( 'mysql:host=localhost;dbname=system', $username, $password );

?>

如果我像这样对表单标签执行操作:

form id="usersForm" method="post" action="insert.php"

数据被发送到数据库但是如果我删除 action="insert.php" 当用户点击提交按钮时没有任何反应。我认为这与我的 Ajax 脚本有关。可能是什么?

这是对您的代码的更正。尝试一下。它有效。

确保包含 jquery 库。

其次,您没有按照

在表单输入中设置电子邮件ID和姓名

id="name" id="email"

第三,您应该删除文本输入周围的表单元素。只需删除它。

<form id="usersForm" method="post">
</form

并像下面这样使用它

     <input type="text" name="name" id="name"/>
       <input type="email" name="email" id="email"/>
 <button type="submit" class="btn btn-success" id="submit" >ADD USER</button>

最后,在 Ajax 调用中,您将变量 EmailName 设置为大写字母,但在您的 php 您将其作为小写字母发布。请注意

修改后的代码如下

        <script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#submit').click(function(){
var Name = $("#name").val();
var Email = $("#email").val();

alert(Name);
alert(Email);

// AJAX code to send data to php file.
    $.ajax({
        type: "POST",
        url: "insert.php",
        data: {Name:name, Email:email},
        dataType: "html",
        success: function(data) {
         alert("Data Inserted Successfully.");
        },
        error: function(err) {
        alert(err);
        }
    });
})
});




</script>

或者你也可以使用我新测试的代码。

        <script src="jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){


    $('#submit').click(function(){
alert('ok');

var name = $('#name').val();
var email = $('#email').val();

//set variables to check for valid email
    atpos = email.indexOf("@");
    dotpos = email.lastIndexOf(".");


        if(name==""){

            alert('please Enter name');


        }

 else if(email==""){

            alert('please Enter Email');


        }


else  if (atpos < 1 || ( dotpos - atpos < 2 ))
    {
        alert("Please enter correct email Address")
        return false;
    }





else{

$('#loader').fadeIn(400).html('<span>Please Wait, Your Data is being Submitted</span>');





var datasend = "nm="+ name + "&em=" + email;

        $.ajax({

            type:'POST',
            url:'insert.php',
            data:datasend,
                        crossDomain: true,
            cache:false,
            success:function(msg){


alert('message successfully inserted');

                //empty name and email box after submission
$('#name').val('');
                $('#email').val('');
                $('#loader').hide();
                $('#alertbox').fadeIn('slow').prepend(msg);
                $('#alerts').delay(5000).fadeOut('slow');

            }

        });

        }

    })

});


</script>






<div id="loader"></div>
 <div id="alertbox"></div>


               <input type="text" name="name" id="name"/>
               <input type="email" name="email" id="email"/>
         <button type="submit" class="btn btn-success" id="submit" >ADD USER</button>

更新部分

试试这个。 ajax 提交成功后会显示成功消息

    <script type="text/javascript">

    $(document).ready(function(){


        $('#submit').click(function(){


    var name = $('#name').val();
    var email = $('#email').val();

    //set variables to check for valid email
        atpos = email.indexOf("@");
        dotpos = email.lastIndexOf(".");


            if(name==""){

                alert('please Enter name');


            }

     else if(email==""){

                alert('please Enter Email');


            }


    else  if (atpos < 1 || ( dotpos - atpos < 2 ))
        {
            alert("Please enter correct email Address")
            return false;
        }





    else{

    $('#loader').fadeIn(400).html('<span>Please Wait, Your Data is being Submitted</span>');





    var datasend = "Name="+ name + "&Email=" + email;

            $.ajax({

                type:'POST',
                url:'insert.php',
                data:datasend,
                            crossDomain: true,
                cache:false,
                success:function(msg){

    if(msg=='success'){
    alert('message successfully inserted');
    }else{
alert('message submission failed');
}
                    //empty name and email box after submission
    $('#name').val('');
                    $('#email').val('');
                    $('#loader').hide();
                    $('#alertbox').fadeIn('slow').prepend(msg);
                    $('#alerts').delay(5000).fadeOut('slow');

                }

            });

            }

        })

    });


    </script>

php 测试文件,例如。 insert.php

<?php


$Name = $_POST['Name'];
$Email = $_POST['Email'];


echo "success";
?>

所以你的 php 文件应该看起来像

<?php

//include('db_connect.php');

$Name = $_POST['Name'];
$Email = $_POST['Email'];


$stmt = $connection->prepare("INSERT INTO users (name, email) VALUES(:name, :email)");

 $stmt->bindparam(':name', $Name);
 $stmt->bindparam(':email', $Email);
 if($stmt->execute())
 {
  //$res="Data Inserted Successfully:";
  //echo json_encode($res);

echo "success";
  }
  else {
 // $error="Not Inserted,Some Probelm occur.";
  //echo json_encode($error);
echo "failed";
  }

  ?>
<input type="text" name="name"/>
<input type="email" name="email"/>

在您的表单中将 ID 属性添加到输入中。

<input type="text" name="name" id="name" />
<input type="email" name="email" id="email" />

或者尝试更改您的 ajax:

var Name = $("#name").val();
var Email = $("#email").val();

var Name = $("#usersForm input[name="name"]").val();
var Email = $("#usersForm input[name="email"]").val();

同时添加e.preventDefault();不刷新页面,after

$(document).on('submit','#usersForm',function(e) {
e.preventDefault();

我也找到了另一种解决方法:

<script>

$(document).on('submit', '#usersForm', function(event){
        event.preventDefault();
    $.ajax({
                url:"insert.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data){
                    alert('OK');
                    $('#usersForm')[0].reset();
                    $('#dataModal').modal('hide');
                }
});
});

</script>