1

How to pass an array from javascript to controller using codeigniter

Here is my code:

view:

function submitFunc(){
  var arrayName = ['John ' , 'Josh' , 'Steph'];
  var arraySerial = [ 123, 456 , 789];

$.ajax({
  type: 'post',
  data: {arrayName:arrayName, arraySerial: arraySerial }, //not sure of this code
  url: '<?= base_url()."mycontroller/insertData"?>',
  success: function(data){
  }
  });
}

and in my controller:

    public function insertData()
      {
          $data = array(
              'Name' =>$this->input->post('arrayName'),
              'Serial' =>$this->input->post('arraySerial '),
          );
          $this->db->insert('test',$data);
      }

trying to achieve something like this n database:

| Name  | Serial|
| John  |   1   |
| Josh  |   2   |
| Steph |   3   |
2

2 Answers 2

1

You should encode the data in json format and then send it to controller

     function submitFunc(){
      var arrayName = ['John ' , 'Josh' , 'Steph'];
      var jsonName = JSON.stringify(arrayName);
      var arraySerial = [ 123, 456 , 789];
      var jsonSerial = JSON.stringify(arraySerial);

    $.ajax({
      type: 'post',
      data: {arrayName:jsonName, arraySerial: jsonSerial }, //not sure of this code
      url: '<?= base_url()."mycontroller/insertData"?>',
      success: function(data){
      }
      });
    }

In you controller

  public function insertData()
  {
      $arrayName = $this->input->post('arrayName');
      $decodeName= json_decode($arrayName,true); // will return an array
      $arraySerial = $this->input->post('arraySerial ');
      $decodeSerial =  json_decode($arraySerial ,true); // will return an array
      for($i=0;$i<=count($decodeName);$i++){
      $data[] = array('Name'=>$decodeName[$i],'Serial'=>$decodeSerial[$i]);
      }

      $this->load->modelName($data);        
  }

in your model

 public function modelName($data){
  $this->db->insert_batch('tablename', $data);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

@StornFrial My pleasure.
0

Try the following controller code to insert data:

$arrayName = $this->input->post('arrayName');
$Serial = $this->input->post('arraySerial');
$data = array();
foreach($arrayName as $key=>$name){
    $data[] = array('Name'=>$name,'Serial'=>$Serial[$key]);
}

$this->db->insert_batch('test', $data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.