Question

I don't want to use the FormHelper from CakePHP, because I want to use some Ajax in my app. How can I pass the data from the form to the Controller? I'm using $.post from jQuery but I always get an error. Thanks!

Was it helpful?

Solution

You can use Ajax with the CakePHP Form Helper.

In your view file .ctp put:

echo $this->Form->create('Model', array('id'=>'YourFormId', array('default'=>false)));
echo $this->Form->input('field');
echo $this->Form->submit('Save');
echo $this->Form-->end

Notice in your form->create your passing a default=>false which tells the form to not do a normal "Submit".

At the bottom of your view file .ctp put:

$data = $this->Js->get('#YourFormId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourFormId')->event(
  'submit',
   $this->Js->request(
      array('action' => 'yourAction', 'controller' => 'yourController'),
      array(
        'update' => '#flash',
        'data' => $data,
        'async' => true,    
        'dataExpression'=>true,
        'method' => 'POST'
        )
      )
     );
    echo $this->Js->writeBuffer(); 

The above is CakePHP JS helper to help you write Ajax and Javascript which PHP. It basically grabs the form data that is being submitted and serializes it and passed it to /yourcontroller/youraction via ajax. The update=>#flash is telling Cake to Update the #flash div after the action is done.

Remember in your Controller to have public

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

OTHER TIPS

-- jQuery --

$.post('<?=$this->Html->url(array('controller'=>'xxx','action'=>'yyy'))?>', {a:1,b:2});

-- cakePHP --

    function yyy() {
       $a = $this->request->data['a'];
       $b = $this->request->data['b'];
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top