Pass Value Onclick Checkbox to controller codeigni

2019-03-04 00:32发布

问题:

I am new to CI and i am having issues in following code: My Controller shows all the values of countries dynamically from DB, i need to pass value onclicking particular chechbox to my controller

My view:

    </head>
    <body>
    <?php 
        foreach ( $countryDetails as $row ) 
        {
        echo '<input id="country" type="checkbox" name="country" class="unique" value="'.$row->country_id.'" onclick="">'.$row->country_name.'<br/>';
        }
        ?>
    <script>
    $('input.unique').click(function() {
    $('input.unique:checked').not(this).removeAttr('checked');
    });
    </script>
    <script>

and my Controller is

public function index()
{       
$this->view_data['countryDetails'] = $this->get_county_model->getCountryDetails();


$this->load->view('get_country' , $this->view_data );
}

回答1:

HTML

  value 1<input type="checkbox" class="chkbox" value="value1"/>
  value 2<input type="checkbox" class="chkbox" value="value2"/> 
  value 3<input type="checkbox" class="chkbox" value="value3"/>
  value 4<input type="checkbox" class="chkbox" value="value4"/>

Jquery Ajax

 $(document).ready(function(){

     $(document).on('click','.chkbox',function(){
      var id=this.value;

       $.ajax({
        type: "POST",
        context: "application/json",
        data: {id:id},
        url: "http://localhost/xyz/index.php/controller_name/function_name",
        success: function(msg) 
        {
            alert('result from controller');
        }
    })
   });

 });

Controller

 public function function_name()
 {
   $id=$this->input->post('id');
   //now use the $id variable for the desired purpose.
 }