如何在cakephp中实现ajax post提交


How to implement ajax post submission in cakephp

我已经上网尝试在cakephp实现ajax后提交,但无济于事,我如何实现这个功能,就像一个在twitter上,我如何更新帖子自动每当有一个新的记录?这是我的邮政编码:

public function add($id = null) {
   if ($this->request->is('post')) {
   $this->request->data['Post']['user_id'] = $this->Session->read('Auth.User.id');
   $this->Post->create();
   if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('The post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'));
}
}
$users = $this->Post->User->find('list');
$this->set(compact('users'));
}

和这是我的邮件形式:

<?php echo $this->Form->create('Post'); ?>
<fieldset>
<legend><?php echo __('Add Post'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('content');
?>
</fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>

尝试Ajax post提交。

将提交按钮代码替换为以下代码:

<?php echo $this->Ajax->submit('SUBMIT',
    array(
        'class'=>'btn', 
        'div'=>false, 
        'label'=>false, 
        'url' => array(
            'controller' =>'your_controller',
            'action' =>'your_function'
        ),
        'update' =>'update_section_id', 
        )
    ); 
?>

Jquery要求:

$('#yourFormId').on('submit', function(event){
  event.preventDefault();
  $.jax({
   type: "post",
   url: "formSubmit",  //your form submission route
   data: {data1: $('input[name="yourInputName"]').val(), //you can add more here},
   dataType: "json",
   cache: false,
   success: function(result){
   //Do something with returned data
}
})
})
控制器

public funtion formSubmit(){
  $this->autoRender = false;
  if($this->request->is('ajax')){
   $data = $this->request->data;
  //Do something with data
  //If save or update successful
  $response = array('status' => 'success', 'msg' => 'your msg');
  return json_encode($response);
}
}