Submit a form with Ajax

Published on January 18, 2006 and tagged with ajax  cakephp  feature  tip

The new release of CakePHP (RC2) comes with a completely rewritten AjaxHelper::form() function (with the disadvantage that it breaks existing code). Let’s look how to use it:

$ajax->form(array('action' => '/controller/action'), 'post',
                     array('update' => 'mydiv'));

I think this code is self-explanatory (if not, please write a comment). What’s cool about this code is the fact that it will also work when you disable JavaScript. The form will submit the form data in both cases to /controller/action. That means you have to distinguish in your action whether it is called via Ajax or not, and then you have at least to select the appropriate layout. You can do it in the following way (thanks to nate for this hint):

$headers = getallheaders();
if (isset($headers['x-requested-with']))
{
    $this->layout = 'ajax';
}

You can access the form data in both cases as you are already used to with

$this->params['data']

That’s it. It is really that simple :)

Update (2006-03-16): The layout selection has changed (you still can use the approach described earlier), the new approach for doing the layout selection is:

class YourController extends AppController
{
    var $components = array('RequestHandler');

    function youraction()
    {
        ... // do something

        $this->RequestHandler->setAjax($this);
    }
}

50 comments baked

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License