Динамическое добавление данных в таблицу с помощью jquery, ajax и codeigniter

мой вопрос:
Я нажимаю кнопку» Добавить » и открываю всплывающую модель boostrap и вставляю данные во всплывающую модель и отображаю эти данные в свою таблицу с помощью jQuery ajax и codeigniter

**Controller Name: Product**

Controller Code Below:

<?php

class Product extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->helper('html');
        $this->load->model('product_model');
        $this->load->library('form_validation');
    }

    public function test() {
        $this->load->view('productlist');
    }

    public function add() {
        $this->form_validation->set_rules('product_name', 'Product Name', 'required');
        $this->form_validation->set_rules('product_category', 'Product Category', 'required');

        if ($this->form_validation->run() == FALSE) {
            echo validation_errors('<li>', '</li>');
        } else {
            $this->product_model->add($_POST);
        }
    }

    public function displaylist() {
        $result = $this->product_model->displaylist();
        echo json_encode($result);
    }

}

?>

Ниже приведен слой вида

Посмотреть: ProductList.РНР

 <form id="myForm" method="post" action="<?php echo site_url(); ?>/Product/add">

     <div id="myModal" class="modal fade" aria-labelledby="exampleModalLabel">
         <div class="modal-dialog">
             <div class="modal-content">
                 <div class="modal-header">
                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                     <h4 class="modal-title" id="exampleModalLabel">New Product</h4>

                 </div>

                 <div class="modal-body">
                     <div id="message" class="text-danger"></div>
                         <label>Product Category:</label>
                         <select class="form-control" id="product_category" name="product_category" id="product_category" value="<?php echo set_value('product_category'); ?>">
                         <option selected="selected" value="Mobile">Mobile</option>
                         <option value="Computer">Computer</option>
                                                            <option value="Cloths">Cloths</option>
                         </select>

                         <label>Product Name:</label>
                         <input type="text" class="form-control" name="product_name" id="product_name" value="<?php echo set_value('product_name'); ?>" required="">
                     </div>
                     <div class="modal-footer">
                         <button type="button" name="submit" id="save_change" class="btn btn-primary" value="">Add Product</button>
                         <button type="button" name="cancel" id="cancel" class="btn btn-default" value="">Cancel</button>
                     </div>
                 </div>
             </div>
        </div>
  </form>


<div class="table-responsive">
     <table class="table table-bordered">

          <thead>
              <tr>
                  <th><input type="checkbox" id="master"></th>
                  <th>Product Category</th>
                  <th>Product Name</th>
                  <th>Edit</th>
                  <th>Delete</th>
              </tr>
          </thead>
          <tbody id="demo">

          </tbody>

          <tfoot>
              <tr>
                  <td>
                      <button type="button" class="btn btn-danger" id="delete_data"><span class="glyphicon glyphicon-remove"></span></button>
                  </td>
              </tr>
          </tfoot>

      </table>
 </div>

Javascript имя файла: практика.js

var productList = {
    mode: "Add",
    add: function () {
        $.ajax({
            url: base_url + "Product/add",
            type: "post",
            data: $("#myForm").serialize(),
            success: function (data) {

            }
        });

    },
    list: function () {
        $.ajax({
            url: base_url + "Product/displaylist",
            success: function (result) {
                var obj = JSON.parse(result);
                // console.log(obj);
                var out;
                var i;
                for (i = 0; i < obj.length; i++) {
                    out += obj[i].product_name;
//                    console.log(obj[i].product_name);
                    var category = '<tr>'
                            + '<td> <input type="checkbox" class="sub_chk"> </td>'
                            + '<td>' + obj[i].product_category + '</td>'
                            + '<td>' + obj[i].product_name + '</td>'
                            + '<td>'
                            + '<a href="#!" data-toggle="modal" data-target="#myModal">'
                            + '<span class="glyphicon glyphicon-pencil"></span></a>'
                            + '</td>'
                            + '<td>'
                            + '<a href="#!">'
                            + '<span class="glyphicon glyphicon-trash"></span></a>'
                            + '</td>'
                            + '</tr>';

                    $("#demo").append(category);

                }
            }

        });
    }
}

$(document).ready(function () {

    productList.list();

    productList.modal = $("#myForm");
    $("#save_change").click(function () {
        if (productList.mode == "Add") {
            productList.add();
        }
    });
});

Скриншот для таблицы продуктов

Скриншот для добавления названия продукта

1 ответ

  1. Дайте id вашей таблицеmyTable, а затем попробуйте.after

    Попробуйте следовать простому коду.

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
    
    
    <table id="myTable">
    <tbody>
        <tr>
            <td>1</td>
            <td>Paresh</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Gami</td>
        </tr>
    </tbody>
    </table>
    
    <button onclick="add()">Add new</button>
    
    </body>
    </html>
    
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    
    <script type="text/javascript">
    
        var index = 3;
        function add()
        {
            $('#myTable tr:last').after('<tr><td>'+(index++)+'</td><td>Paresh Gami</td></tr>'); 
        }
    
    </script>