Codeigniter select box value not pass to controller using ajax

醉酒当歌 提交于 2019-12-12 05:40:05

问题


Am trying to pass the select-box value to controller but value not pass This is my code

<select class="form-control" name="product_id" onchange="getProduct(this.value)">
    <option>--Select Payment--</option>
    <option value="<?php echo $product['sno']; ?>"><?php echo $product['product_name']; ?></option>
</select>
<script type="text/javascript">
function getProduct(product_id) {

    $.ajax({
        url: "<?php echo base_url(); ?>customer_order/getproduct",
        type: "POST",
        data: {
            id: product_id,
        }
    }).done(function(data) {
        $('product_id').val(data);
        alert(product_id);
    });
}

   </script>

Controller:

class Customer_order extends CI_Controller {
  function getproduct(){
   $data = $this->input->post('id');
   echo '<script type="text/javascript">alert("'.$data.'");</script>';
   $this->load->view('create_customer_order',$data);
  }
}

How can i pass the value to controller using ajax ?


回答1:


Pls do make some changes in ur code as follows

<select class="form-control" name="product_id" id="product_id">
    <option>--Select Payment--</option>
 <?php foreach($product as $prod){ ?>

     <option value="<?php echo $prod['sno']; ?>"><?php echo $prod['product_name']; ?></option>

<?php } ?>

</select>





<script>
$('#product_id').on('change', function(){
   var proId = $('#product_id option:selected').val();
 if(proId != null){

    var url = "<?php echo base_url(); ?>customer_order/getproduct";
            var proResult = $.ajax({
                                            url: url,
                                            data: {'id': proId },
                                            type: 'post',
                                            dataType: 'json'
                                        });
                proResult.done(function(data){
//                 console.log('data', data);
//                 alert(data);
//                 Here..Do something as you wish

                });
 }
});

</script>

I think this is only the reference code for getting an idea about how to pass data to controller and return the result to the view page using ajax and json

In the controller there should be function

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Customer_order extends CI_Controller {

    function __construct() {
        parent::__construct();


    }

    function getproduct() {
     $data = $this->input->post('id', true);
     header('Content-Type: application/x-json; charset=utf-8');
     echo(json_encode($data));

    }
} ?>

I hope this may helps you. Thanks!



来源:https://stackoverflow.com/questions/45443363/codeigniter-select-box-value-not-pass-to-controller-using-ajax

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