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

时间:2013-08-31 21:45:02

标签: php jquery ajax post codeigniter-2

我是使用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>

1 个答案:

答案 0 :(得分:1)

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);

    }
});