Dev
Dev

Reputation: 1746

How to save multiple rows using jquery ajax in CI

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

Upvotes: 0

Views: 4566

Answers (3)

Ilanus
Ilanus

Reputation: 6928

I have created a function for you that will loop and asign your inputs.

$('#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 arr = [];
  $(".row").each(function(index) {
  var text   = $(this).find('input[type=text]').eq(index).val();
  var number = $(this).find('input[type=number]').eq(index).val();
   arr.push({
      text: text,
      number: number
   });
});

$.ajax({
      type: "POST",
      url: BASE_URL+'save/saverows',
      data: {batch:arr},
      async: false,
      success: function(data){
          alert('Rows saved!');
      }
  });
});

In you Controller you do

public function saveRows(){
$this->db->insert_batch('savehere', $this->input->post('batch'));
}

'savehere' replace to your table name

We made the array before in the jQuery in your database structure so it has to be inserted nice and short code.

Depending on your database structure

arr.push({
   text: text,
   number: number
});

or if in your database uppercase then

arr.push({
   TEXT: text,
   NUMBER: number
});

Upvotes: 2

jagad89
jagad89

Reputation: 2643

At server end we need to generate array of rows like shown here

//Save
$('#save').on('click',function(){
    var data = [];
    $('.text').each(function(index){
        // text and number are datatypes in database. so i mentioned respected column name
        var row = { "text_col": $(this).val(), "number_col": $('.number')[index].val()   }; 
   data.push(row);
     });

    $.ajax({
          type: "POST",
          url: BASE_URL+'save/saverows',
          dataType: 'json',
          data: data,
          async: false,
          success: function(data){
        if(data == "done"){
        alert('Rows saved!');
        }
    }
  });
});

Controller:

public function saveRows(){
    if ($this->input->is_ajax_request()){
    $data = $this->input->post();
    // I assume row_model already loaded by you.
    $this->Row_model->saveAll($data);
    $this->output->set_output("done");
    }
    $this->output->set_output("failed");
}

Inside Row_model

public function saveAll($data){
    $this->db->insert_batch('table_name', $data);
 }

I hope this will helps. I have not tested code. So if you find any problem feel free to edit.

Upvotes: 0

Pravesh Mehta
Pravesh Mehta

Reputation: 228

Take name and ID of every input field, which should be unique Send the form by serializing to controller

Upvotes: 0

Related Questions