Top Menu

ajax scripts script web 2.0 dhtml javascript

Main Menu

Menu

Scripts

 
Category: Ajax Form Scripts /  Submit A Form With Ajax

Submit a form with Ajax

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


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);
    }
}

http://cakebaker.wordpress.com/2006/01/18/submit-a-form-with-ajax


Hit: 12345.



 
Write Review

Footer