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

问题描述 投票:0回答:3

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

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

我的表有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表上插入数据的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脚本有关的东西。会是什么呢?

php mysql ajax insert-into
3个回答
1
投票

这是对代码的更正。试试吧。有用。

确保包含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调用中,您将变量Email和Name设置为大写字母,但在您的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";
  }

  ?>

1
投票
<input type="text" name="name"/>
<input type="email" name="email"/>

在您的表单中,将ID attr添加到输入。

<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();为了不刷新页面,之后

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

0
投票

我找到了解决这个问题的另一种方法:

<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>
© www.soinside.com 2019 - 2024. All rights reserved.