开发者

codeigniter 2.0 and ajax

I just want to store a variable from jQuery into a session.

js file:

$.post("controller/ajaxtest","hello");
开发者_运维问答

I am able to see this post request in firebug. How can I access this variable or store it in the session?


Change the data you are sending to a JSON object or a query string, then you can access it in PHP via $_POST or CodeIgniter's $this->input->post

$.post("controller/ajaxtest","var=hello");

OR

$.post("controller/ajaxtest",{"var":"hello"});

Then in ajaxtest, you can access it via $this->input->post('var').

NOTE: If you do $.post("controller/ajaxtest","hello");, you are sending a post variable called hello with no value ($_POST['hello'] will exist, but be empty).

UPDATE: To get this value back in your JavaScript, you can either make another AJAX call to a PHP script to retrieve it, or you can pass it to your view from the controller.

AJAX Method:

CI Controller

function getval(){
  $data = array('val' => 'Hello');
  echo json_encode($data);
}

JavaScript

$.getJSON("controller/getval", function(data){
  alert(data.val); //Hello
});

Controller -> View Method:

CI Controller

function index(){
  $data['val'] = 'Hello';
  $this->load->view('page', $data);
}

And then in your view:

<script>
  var val = '<?=$val?>';
  alert(val); //Hello
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜