4

I'm having trouble building an ajax form in cakephp 2 which obviously has changed a lot since 1.3.

I'm using the following code:

<div id="commentForm">
<div id="commentStatus"></div>
<?php
echo $this->Form->create('Comment', array('action' => 'save', 'default' => false));
echo $this->Form->input('Comment.comments_name');
echo $this->Form->input('Comment.comments_email');
echo $this->Form->input('Comment.comments_text');
echo $this->Js->submit('Save', array('update' => '#commentStatus'));
echo $this->Form->end();
?>

However the form is not submitted when pressing the button.

I will be thankful for any help!

Thanks!

DIDoS
  • 812
  • 9
  • 23
Kik Minev
  • 103
  • 1
  • 3
  • 9

2 Answers2

11

Try this in your view file:

<?php

    $data = $this->Js->get('#CommentSaveForm')->serializeForm(array('isForm' => true, 'inline' => true));
    $this->Js->get('#CommentSaveForm')->event(
          'submit',
          $this->Js->request(
            array('action' => 'save'),
            array(
                    'update' => '#commentStatus',
                    'data' => $data,
                    'async' => true,    
                    'dataExpression'=>true,
                    'method' => 'POST'
                )
            )
        );
    echo $this->Form->create('Comment', array('action' => 'save', 'default' => false));
    echo $this->Form->input('Comment.comments_name');
    echo $this->Form->input('Comment.comments_email');
    echo $this->Form->input('Comment.comments_text');
    echo $this->Form->end(__('Submit'));
    echo $this->Js->writeBuffer();

?>

NOTE: #CommentSaveForm is ID generated by CakePHP, If you have your own then use that

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
2

You want to show the loading image, use 'before' and 'complete' in $this->Js->request():

<?php
    $this->Js->request(array('action' => 'save'), array(
       'update' => '#commentStatus',
       'data' => $data,
       'async' => true,    
       'dataExpression' => true,
       'method' => 'POST',
       'before' => "$('#loading').fadeIn();",
       'complete' => "$('#loading').fadeOut();",
   ));
?>
Sirko
  • 72,589
  • 19
  • 149
  • 183
steveteuber
  • 182
  • 6