如何使用Ajax和PHP从动态文本框中插入数据?

时间:2018-05-18 03:47:11

标签: php jquery mysql ajax

我的bootstrap模式中有一个动态文本框,但它只保存第一个项目。但是,我尝试使用本机提交而不使用Ajax,它捕获所有输入的数据。我无法弄清楚我的Ajax代码出错了。我只想插入从动态文本框输入的所有数据,而无需重新加载页面。这是我的示例代码:

 <!-- start dynamic fields for parameter -->
    <div class="row">
        <div class="col-md-12">
          <div class="input-group control-group after-add-more">
          <?php require 'lab/pardrop.php'; ?> <!--dropdown list for parnam-->
          </select>
         <input type="text" name="parval[]" class="form-control" id="parval" 
               placeholder="Value" >
         <button class="btn btn-success addmore" type="button" data- 
               toggle="tooltip" title="Add Parameter">
            <i class="glyphicon glyphicon-plus"></i></button>
        </div>
        </div>
    </div>
<!--start hidden fields-->  
     <div class="row">
        <div class="col-md-12">
          <div class="copy-fields hide">
            <div class="control-group input-group">
             <?php require 'lab/pardrop.php'; ?> <!--dropdown list for parnam-->
              </select>
              <input type="text" name="parval[]" id="parval" class="form- 
                 control" placeholder="Value" >
                <button class="btn btn-danger remove" type="button">
                  <i class="glyphicon glyphicon-remove"></i></button>
            </div>
        </div>
        </div>
    </div> 
<div class="modal-footer">
     <button class="btn btn-info" type="button" name="btnsamp2" 
      id="btnsamp2"> 
</button>
 </div>  

<!--Ajax code-->

<script>
    $(document).ready(function(){

        $("#btnsamp2").click(function(){
          var parnam=$("#parnam").val();
          var parval=$("#parval").val();

          $.ajax({
                url:'insamp2.php', 
                method:'POST',
                data:{
                      parnam:parnam,
                      parval:parval
                    },
                   success:function(data){
                       alert(data);
                   }
                });
            });
        });
</script>

<!--PHP Code-->

<?php
  //insamp2.php
  require 'lab/db/dbcon.php';
  $num = count($_POST["parnam"]) OR ($_POST["bacnam"]);
  $parnam=mysqli_escape_string($con, $_POST['parnam']);
  $parval=mysqli_escape_string($con, $_POST['parval']);


  if($num > 0){  
      for($i=0; $i<$num; $i++)  
      {  
           if($_POST["parnam"][$i] != '' && $_POST["parval"][$i] )  
           {  

            $sql = "INSERT INTO pardtls(parnam,parval) VALUES ('".$parnam[$i]."','".$parval[$i]."')";
              mysqli_query($con, $sql);

           }  
      } 
          echo "Parameter inserted";  
     }  
     else  
     {  
          echo "Failed inserting data";  
     } 

?>

1 个答案:

答案 0 :(得分:0)

下面的代码序列化所有相关的输入数组,以便将它们的值传递给php处理程序。

您可以使用此jquery代码:

<script>
    $(document).ready(function(){

        $("button[name='btnsamp2']").click(function(){
          $.ajax({
                url:'insamp2.php', 
                method:'POST',
                data: $('input[name="parval[]"]').serialize() + '&' + $('input[name="parnam[]"]').serialize(),
                   success:function(data){
                       alert(data);
                   }
                });
            });
        });
</script>

或者,您可以将input tags括在<form>代码中。

然后使用这个jquery代码:

<script>
    $(document).ready(function(){
        $("button[name='btnsamp2']").click(function(){
          $.ajax({
                url:'insamp2.php', 
                method:'POST',
                data: $('form').serialize() + '&submit=1',
                   success:function(data){
                       alert(data);
                   }
                });
            });
        });
</script>

在PHP脚本中有一些错误。你错误地计算了传入的$_POST变量的元素。

$num = count($_POST["parnam"]) OR ($_POST["bacnam"]); // bad counting.. fixed it in the code below.

您在mysqli_real_escape_string(..)数组值上执行$_POST会导致错误,并且还会将所需的值渲染为空。

同样在下面的代码中添加了正确的插入警报。

试试这个更新的PHP代码

<?php
  require 'lab/db/dbcon.php';
  $num = isset($_POST['parnam'])?count($_POST['parnam']):0;
  $contid=mysqli_escape_string($con, $_POST['contid']);
  $sampno=mysqli_escape_string($con, $_POST['sampno']);
  $statno=mysqli_escape_string($con, $_POST['statno']);
  $statname=mysqli_escape_string($con, $_POST['statname']);
  $coltime=mysqli_escape_string($con, $_POST['coltime']); 
  $parnam=isset($_POST['parnam'])?$_POST['parnam']:array();
  $parval=isset($_POST['parval'])?$_POST['parval']:array();
  $bacnam=isset($_POST['bacnam'])?$_POST['bacnam']:array();
  $bacval=isset($_POST['bacval'])?$_POST['bacval']:array();

  $sql="INSERT INTO samp (contid,sampno,statno,statname,coltime) VALUES ('$contid', '$sampno','$statno','$statname','$coltime')";
  if ($con->query($sql) === TRUE && $sampno!="" && $statno!="" ) {
      echo "Success! Data inserted";
  }
  else 
  {
      echo "Failed! Please input data!";
  }

  if($num > 0){  
      for($i=0; $i<$num; $i++)  
      {  
           if($_POST['sampno'] && $_POST["parnam"][$i] != '' && $_POST["parval"][$i] != '' && $_POST["bacnam"][$i] != '' && $_POST["bacval"][$i] != '')  
           { 
              $parnam[$i]=mysqli_escape_string($con, $parnam[$i]);
              $parval[$i]=mysqli_escape_string($con, $parval[$i]);
              $bacnam[$i]=mysqli_escape_string($con, $bacnam[$i]);
              $bacval[$i]=mysqli_escape_string($con, $bacval[$i]);

            $sql = "INSERT INTO pardtls(sampno,parnam,parval,bacnam,bacval) VALUES ('".$sampno."','".$parnam[$i]."','".$parval[$i]."','".$bacnam[$i]."','".$bacval[$i]."')";
            $inserted = mysqli_query($con, $sql);
            if($inserted === false){
                echo "A record not inserted at index $i ..<br/>\n";
                echo mysqli_error($con)."<br/>\n";
            }

           }  
      } 
     }  
     else  
     {  
          echo "Failed! Please input data";
     } 
?>