In this article I will describe how you can submit a form with Ajax and CakePHP 1.2.x (this is a rewrite of an article I wrote for a very early version of CakePHP, you can find the original article below).
To use CakePHP’s Ajax helper you need the Prototype and script.aculo.us JavaScript frameworks (place the files to app/webroot/js). Those Javascript files have to be included in the “head” section of your layout (e.g. app/views/layouts/default.ctp) with:
<?php echo $javascript->link(array('prototype', 'scriptaculous')); ?>
In the snippet above we use the JavaScript helper, and for submitting the form we will use the Ajax helper, so we have to specify those helpers in either our controller or in our AppController with:
public $helpers = array('Javascript', 'Ajax');
Defining our form is very similar to defining a “normal” form:
<?php
echo $ajax->form('action', 'post', array('update' => 'mydiv'));
// add form elements
echo $form->end();
?>
<div id="mydiv">
This will be replaced with the ajax response
</div>
To avoid that the Ajax response gets rendered with the layout we use for the view, we have to add the RequestController to our controller. It will automatically select the Ajax layout when a controller action is called via Ajax.
public $components = array('RequestHandler');
The final step is to implement the action which handles the form data. It is done in the same way as with “normal” form data, so I leave this as an exercise for you ;-)
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);
}
}

$headers = getallheaders();
if (isset($headers['x-requested-with']))
mmmh… it looks ugly still.
how about putting this in a beforeFilter in app_controller?
yup works pretty nicely in the beforeFilter. Only thing i had to change was the case.
$headers['X-Requested-With']
I played around some more. I think this mught be the a good solution as well.
if (env(‘HTTP_X_REQUESTED_WITH’))
{
$this->params['bare'] = ’1′;
}
@gwoo: thanks for the tips!
Even better, I’m working on a new Cake component to help manage different types of requests. At some point, it will be added to the core. For now, you can download it at:
http://cakephp.org/pastes/show/5c65b074ae8f693407709b4b9ada1496
Just add the component to your controller:
var $components = array(‘Request’);
And put this in your beforeFilter( ) :
$this->Request->setAjax($this);
Also, the $ajax->form method doesn’t like to work with some browsers. I have found that the $ajax->submit likes a much broader range of browsers.
$ajax->submit(‘submit’, ‘Submit’, array(‘url’ => ‘action’, ‘update’ => ‘div’));
[...] cake baker » Submit a form with Ajax (tags: ajax) [...]
[...] 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. [...]
[...] La lista la componen tutoriales con técnicas diferentes, como tutoriales para arrastrar y soltar, hacer carritos de compra, formularios, herramientas para subir archivos y unos cuantos más. [...]
that’s good
[...] Submit a form with Ajax [...]
[...] Submit a form with Ajax [...]
[...] Submit a form with Ajax [...]
[...] Submit a form with Ajax [...]
[...] Submit a form with Ajax The new release of CakePHP (RC2) comes with a completely rewritten AjaxHelper::form() function (with the disadvantage that it breaks existing code). [...]
cake baker Submit a form with Ajax
The new release of CakePHP (RC2) comes with a completely rewritten AjaxHelper::form() function (with the disadvantage that it breaks existing code). Lets look how to use it:
col.
this is really nice
cool
Is there a way to submit “multipart/form-data” forms with CakePHP / Ajax ?
I can’t manage uploading files this way… Is there a trick or is it just impossible ?
@Sam: No, it is not possible to upload files with Ajax due to security restrictions in the browser (it is not allowed for Javascript to access the local file system). I think you have to use IFrames to get a similar effect.
Hi How are You?
[...] Submit a form with Ajax The new release of CakePHP (RC2) comes with a completely rewritten AjaxHelper::form() function (with the disadvantage that it breaks existing code). [...]
[...] Submit a form with Ajax [...]
great!
great
nice
[...] Submit a form with Ajax : at CakeBaker [...]
Hi,
I Just want to know how to deal with the event handlers while sub,itting a form using Ajax !
@Mahul Banerjee: Hm, what event handlers are you talking about?
Wish i could get this to work
@Phunky: What’s the problem?
I think the problem is more to do with myself hating JavaScript and in turn hating Ajax :)
I’m just trying to do a simple submission of a comment form, that once submitted will update the comments displayed.
I’ll keep at it, when i posted the above comment i was still trying to get my head around CakePHP :)
@Phunky: Just curious, but why do you something you hate? ;-)
Anyway, good luck :)
Heh :) Well my hate for JavaScript goes back to the days when DHTML first came around and people went mental over it, but sadly it was nightmare to get working over all browsers (NN4.5 urgh!)
I avoided JavaScript like the plague, but over the past 18months ive seen more and more people adopt AJAX and although its got some great uses and is now more workable its still JavaScript and it still racks my brain when i attempt to use it :)
[...] Max Kiesler has published in his blog a list of 30 Ajax tutorials. If you use Ajax, I am sure you will find in this list some new ideas. I am especially happy about the fact that one of these 30 tutorials is an article I wrote in this blog two months ago (”Submit a form with Ajax“). [...]
[...] http://cakebaker.42dh.com/2006/01/18/submit-a-form-with-ajax/ CakeBaker’s blog on Submitting A Form With Ajax is a small but resourceful blog to read, especially the comments. [...]
excellent
Programming Tutorials…
I couldn’t understand some parts of this article, but it sounds interesting…
[...] of the web framework like Django or CakePHP, you’ll appreciate the tutorial by CakeBaker on how to submit a form with Ajax. It’s actually quite simple to do, and only requires a few lines of code. One especially useful [...]
[...] sei un utente del web framework come Django o CakePHP, avrai apprezzato il tutorial di CakeBaker su come presentare un modulo con Ajax. In realtà è abbastanza semplice da fare e richiede solo [...]
[...] web framework like Django or CakePHP, you’ll appreciate the tutorial by CakeBaker on how to submit a form with Ajax. It’s actually quite simple to do, and only requires a few lines of code. One especially [...]
[...] web framework like Django or CakePHP, you’ll appreciate the tutorial by CakeBaker on how to submit a form with Ajax. It’s actually quite simple to do, and only requires a few lines of code. One especially [...]
?php $ajax->form(array(‘action’ => ‘/interpreter_inqueries/add’), ‘post’, array(‘update’ => ‘mydiv’)); ?>
when i am trying to use the above code then the following error i get and also many of my friends got it.
Notice (8): Array to string conversion [CORE\cake\libs\router.php, line 1051]
So how can i recover it.
Thanks
Arafat
@arafat: Thanks for your comment!
It seems to be a bug, and so I opened a ticket for it here.
The following code should work:
$ajax->form(null, 'post', array('update' => 'mydiv', 'url' => array('controller' => 'interpreter_inqueries', 'action' => 'add')));Hope that helps!
GRE@T
[...] 如果你是 Django 或 CakePHP的使用者,那么你应该要感谢CakeBaker 的这个教程——《how to submit a form with Ajax》,而它最强大的功能在于,如果我们的浏览器disable了Javascript,表单照样能够正常提交。 [...]
hi hw can i add yotube video to my php site means hw embedding can be done
@parth: Have a look at http://stackoverflow.com/questions/412467/how-to-embed-youtube-videos-in-php.
[...] web framework like Django or CakePHP, you’ll appreciate the tutorial by CakeBaker on how to submit a form with Ajax. It’s actually quite simple to do, and only requires a few lines of code. One especially [...]
I tried on cakePHP 1.2.5, view code doesn’t work
@Amit: I just updated the article as it contained some outdated stuff. I hope this solves the issue you encountered.
[...] This post was mentioned on Twitter by Kingsley. Kingsley said: http://tinyurl.com/5f5vwf Submit a form with Ajax – cakebaker [...]