无法从codeigniter中的ajax帖子中检索变量


Unable to retrieve variables from ajax post in codeigniter

我是ajax的新手,在控制器中发布变量和访问这些变量时遇到了问题。

这是控制器代码

class autocomplete extends CI_Controller {
  // just returns time
  function workdammit()
  {
    $product = $this->input->post('productName');
/*      $this->load->model('product_model');
    $q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
    $data = $this->product_model->get_record_specific($q);
    echo json_encode($data[0]->quantity);
*/
    echo $product;
  }
  function index()
  {
    $this->load->view('autocomplete_view');
  } 
}

如果我将echo更改为像'Hello World'这样的单引号内的字符串,它将正确地将hello world返回到视图中。但如果我像现在这样尝试,它将不会起到同样的作用。此外,如果我使用echo json_encode($product);,它将返回false。

下面是使用ajax的视图代码。

$( document ).ready(function () {
  // set an on click on the button
  $('#button').click(function () {
        $.ajax({
    type: "POST",
    url: "<?php echo site_url('autocomplete/workdammit'); ?>",
    dataType: "json",
    data: 'productName',
    success: function(msg){  
        alert(msg);
    }
    });
  });
});
</script>
</head>
<body>
  <h1> Get Data from Server over Ajax </h1>
 <br/>
  <button id="button">
     Get posted varialbe
 </button>
class autocomplete extends CI_Controller {
// just returns time
    function workdammit()
    {
        $product = $this->input->post('productName');
        //echo $product;
        //in ajax dataType is json -here You have to return json data
        echo json_encode($product);
    }
...
}    
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
    $.ajax({
    type: "POST",
    url: "<?php echo site_url('autocomplete/workdammit'); ?>",
    dataType: "json",
    data: {productName:productName},//You have to send some data from form
    success: function(msg){  
        alert(msg);
    }
});