使用 ajax 和 php 从数组表中在数据库中插入值


Insert values in database from array table using ajax and php

帮助我使用 ajax 和 php 从我的表中的数组输入中插入数据。我有单独的 php 文件,但目前它是空白的。

这是我当前的HTML + PHP代码:

<form class='form-horizontal form-validate' id="form">
<?php
echo "<table id='example' class='table table-bordered'>
<thead>
<tr>
<th>Category</th>
<th>Last Qtr Average time</th>
<th>Target time</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Category</th>
<th>last Qtr Average time</th>
<th>Target time</th>
</tr>
</tfoot>
<tbody>";
$get_category_query = "select * from daily_checklist_category order by category asc";
$get_category_result = mysql_query($get_category_query) or die(mysql_error());
while($count_rows = mysql_fetch_row($get_category_result)){
echo'<tr>';
echo'<td>'.$count_rows[1].'</td>';
echo'<td id="fucktime[]">'.$count_rows[2].'</td>';
echo'<td><input type="text" value="'.$count_rows[3].'" id="cat_rows[]"/></td>';
echo'</tr>';                                    
}
echo "</tbody>
</table>";
?>
<div class="form-actions">
<input type="submit" id="finish" class="btn btn-primary" value="Submit">
</div>

这是我的阿贾克斯:

$(document).ready(function(){
  $('#form').ajaxForm(function(){
    //$("#loading").fadeIn();
    var catRows = $('#cat_rows[]').val();
    $.ajax({
        type: "GET",
        data: $('#form').serialize(),
        url: 'pages/scripts/insert_daily_checklist_category.php',
        cache: false,
        success:function(data){
            alert('Daily Checklist Categories are now updated.');
        }
    });
  });
});

需要帮助。

代码中的问题是,您没有在输入字段中使用名称字段:

<input type="text" value="'.$count_rows[3].'" id="cat_rows[]"/>

这应该是:

<input type="text" name="cat_rows[]" value="'.$count_rows[3].'" id="cat_rows"/>

在jQuery中:

您需要获取此值,如下所示:

var catRows = $('#cat_rows').val();

旁注:

我假设您在原始文件中使用结束标签。

也可以使用 mysqli_PDO,因为mysql_扩展已被弃用,并且在 PHP 7 中不可用。

首先像这样将 name 属性添加到输入表单元素中。

echo '<td><input type="text" name="cat_rows[]" value="'.$count_rows[3].'" id="cat_rows_'.$count_rows[3].'"/></td>';

而且你已经在使用 ajaxForm jquery,所以不需要任何其他将 ajax 语句写入回调。你的ajaxForm jquery是这样的。

j查询示例-

// bind form using 'ajaxForm' 
$('#form').ajaxForm({
  url: 'pages/scripts/insert_daily_checklist_category.php',
  beforeSubmit: function(formData, jqForm, options) {
    // write code here like loader if needed
  },
  success: function(responseText, statusText, xhr, $form) {
    // write code for response handling
  }
});