Save data from dynamically created rows to database

后端 未结 1 731
时光说笑
时光说笑 2021-01-27 09:30

I am using Codeigniter. I have created a table that contains different columns. I wanted to create rows dynamically when clicking on the \'+\' button. Now i am able to create ro

相关标签:
1条回答
  • 2021-01-27 10:03

    You can use ajax request on this.

    First when you click + button, instead of just text in each column, you can put input fields.

    <tr>
     <td><input id="field1" type="text" /></td>
     <td><input id="field2" type="text" /></td>
     <td><input id="field3" type="text" /></td>
     <td><button id="save"></button></td>
    <tr>
    

    After that, you can assign an event to the button#save. When it is click, it will get all the inputs from the fields then store in variable and call an ajax request. You should prepare a php code to handle this request.

    $('#save').on('click', function() {
       var data = { 
           field1: $('input#field1').val(), 
           field2: $('input#field2').val(), 
           field3: $('input#field3').val()
       };
    
       // call ajax request
       $.post(url + '/controller/save', data, function(data) {
          console.log(data);
       }); 
    } 
    

    In your controller you should have that save method that handle the request.

    public function save() {
        if($_POST) {
          // get input
          // call model to save data to db
        }
    }
    

    Updated Here

    You can have a button save to save all the data.

    $('#save').click(function() {
        var data = $('input').serialize();
    
        $.post(url, data, function(data) {
           console.log(data);
        }); 
    });
    

    Then just use print_r or var_dump to see the posted values in your method in controller.

    0 讨论(0)
提交回复
热议问题