将数据插入我的CRUD表

时间:2017-10-31 04:12:53

标签: javascript php jquery html ajax

我有这个AJAX代码,它会将数据插入我的CRUD表。但是,当我单击将保存/插入数据到我的表的按钮时,它将不会显示。我想要的就是使用AJAX将我的数据插入到我的表中,而无需刷新或使用html中的表单元素。

这是我的模态和我的表格的代码:

$(document).ready(function() {
  // Add
  $('#btn_add').click(function() {
    var id = $('#brand_id').val();
    var bname = $('#bname').val();
    var bstatus = $('#bstatus').val();

    $.ajax({
      url: 'add_brand.php',
      method: 'POST',
      data: {
        bname: bname,
        bstatus: bstatus
      },
      success: function(data) {
        $('#' + id).children('td[data-target=brand_name]').text(bname);
        $('#' + id).children('td[data-target=brand_status]').text(bstatus);
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade" id="modal-default">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Add a brand</h4>
      </div>
      <div class="modal-body">
        <input type="hidden" id="brand_id" />
        <div class="form-group">
          <label for="bname">Brand Name</label>
          <input type="text" class="form-control" id="bname" name="bname" placeholder="Brand Name" />
        </div>
        <div class="form-group">
          <label for="bstatus">Status</label>
          <select class="form-control select2" style="width: 100%;" id="bstatus" name="bstatus">
                                <option>Available</option>
                                <option>Not Available</option>
                            </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" id="btn_add">Save Changes</button>
      </div>
    </div>
  </div>
</div>

<tbody>
    <?php 
        include("db_connect/connect.php");

        $query = mysqli_query($con, "SELECT * FROM brand");
        while ($row = mysqli_fetch_array($query)) { ?>
            <tr id="<?php echo $row['brand_id']; ?>">
                <td data-target="brand_name"><?php echo $row["brand_name"]; ?></td>
                <td data-target="brand_status"><?php echo $row["brand_status"]; ?></td>
                <td>
                    <a data-role="edit" data-id="<?php echo $row['brand_id']; ?>" class="btn btn-success"><i class="fa fa-edit"></i> Edit</a>
                    <a href="brand.php" data-role="delete" data-id="<?php echo $row['brand_id']; ?>" class="btn btn-danger"><i class="fa fa-trash-o"></i> Delete</a>
                </td>
            </tr>
        <?php
        }
    ?>
</tbody>

0 个答案:

没有答案