Save data from dynamically created rows to database

怎甘沉沦 提交于 2020-01-22 03:43:47

问题


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 rows using jquery. I want to save the data to database. how can i save the values of each rows to database when i click on the '+' button?


回答1:


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.



来源:https://stackoverflow.com/questions/38006855/save-data-from-dynamically-created-rows-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!