cakephp 2.3 ajax表单提交

时间:2013-06-13 16:08:45

标签: php ajax jquery cakephp cakephp-2.0

我正在尝试创建一个使用ajax将数据提交到数据库的简单表单。这是我的观点

  <?php echo $this->Html->script('jquery', FALSE); ?> 
<?php echo $this->Html->script('validation', FALSE); ?>
  <div id="success"></div>
  <h2>Contact Us</h2>

  <?php
   echo $this->Form->create();
   echo $this->Form->input('name', array('id'=>'name'));
   echo $this->Form->input('email', array('id'=>'email'));
   echo $this->Form->input('message', array('id'=>'message'));
   echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
 ));
 echo $this->Form->end();
  ?>
   <div id="sending" style="display: none; background-color: lightgreen;">Sending...</div>

控制器

    class MessagesController extends AppController{

public $helpers = array('Js');
public $components = array('RequestHandler');

public function index(){

  if(!empty($this->data)){
      if($this->Message->save($this->data)){
          if($this->request->isAjax()){
             $this->render('success','ajax');
          }else{


         $this->Session->setFlash('Message sent');
         $this->redirect(array('action'=>'index'));
      }
      }
  }
 }

 }

它不是通过ajax发送表单..实际上我是cakephp的新手,这是我第一次在cakephp中使用ajax。而且我想知道我可以使用codeigniter或简单的PHP类似语法的蛋糕php中的表单提交。例如像这样

  <script>

 $('#btn').click(function(event) {
       form = $("#form").serialize();

     $.ajax({
       type: "POST",
       url: "<?php  echo site_url('categoryController/addCategory'); ?>",
       data: form,

       success: function(data){
           $('.modal').modal('hide');
           $(".success").fadeIn(500).delay(2000).fadeOut(500);
           $("#form")[0].reset();
           //Unterminated String constant fixed
       }

     });
     event.preventDefault();
     return false;  //stop the actual form post !important!

  });

</script>

1 个答案:

答案 0 :(得分:0)

我得到了答案。我错过了jquery.js档。