In my html, rows are added dynamically by pressing a button.
<button id="add-row">Add New Row</button>
<div class="container">
<div class="row"><!-- Begins with 1 row -->
<input type="text" class="text"><input type="number" class="number">
</div>
<div class="row"><!-- IF user adds 1 row -->
<input type="text" class="text"><input type="number" class="number">
</div>
</div>
<button id="save">Save</button>
In my jQuery
//Add row
$('#add-row').on('click',function(){
$('.container').prepend('<div class="row">'+
'<input type="text" class="text"><input type="number" class="number">'+
'</div>');
});
//Save
$('#save').on('click',function(){
var text = $('.text').val();
var number = $('.number').val();
$.ajax({
type: "POST",
url: BASE_URL+'save/saverows',
dataType: 'html',
data: {text:text,number:number},
async: false,
success: function(data){
alert('Rows saved!');
}
});
});
In my CI Controller
public function saveRows(){
$data = array(
'text' => $this->input->post('text'),
'number' => $this->input->post('number')
);
$this->Row_model->saveAll($data);
}
In my CI Model
public function saveAll($data){
$this->db->insert('savehere', $data);
}
Database table looks like this
ID TEXT NUMBER
1 a 11
2 b 22
3 c 33
4 d 44
What I have is just for saving a single row only. How can I accomplish this if there are more than 1? I have an idea of using loop but I do not know how to implement it here. I've also read about CI's inserting by batch but it has a fixed number of rows to be saved.
My problem is in the #save onclick. How to retrieve all the text and number values and then pass it to jquery ajax then to codeigniter controller.
Using Ilan Hasanov's answer below. The console.log of the arrays is:
for (var i = 0; i < arrText.length; i++) {
console.log(arrText[i]+" "+arrNumber[i]);
}
text 100
text2 55
dataType: 'html'todataType: 'json'data :{}look like?jsonobject. Do it and it will work as expected.