Creating Ajax form in Cakephp using jQuery

Because of its being more flexible, extensible and precise nature the jQuery certainly has emerged as a more popular Javascript library as compared to prototype library. If you plan your Cakephp application depend heavily on Javascript, its right time to chose jQuery for your cakephp-cum-javascript needs.

(If you are already using Prototype with cakephp you may want to look at how to create ajax form with prototype in Cakephp)

Although you may find some good jQuery Ajax Helpers for Cakephp around (Here is one although i have’t tried it yet) i still use the jQuery’s conventional ajaxForm plugin to submit ajax forms in Cakephp. Here’s quick note how to do it.

Download ajax form plugin for jQuery from here and place “jquery.form.js” in your webroot/js/ directory. Make sure you already have placed jQuery library file(s), at least one of them in the webroot/js/ directory. In my case, i had “jquery-1.3.2.min.js” in my webroot/js directory.

Include main jQuery library file in the <head> section of your web page. I included at least two files like the following:

With this first step done we are now prepared to make ajax form work in cakephp. Lets create a (ajax) form in our view file (whatever it is may be home page) which we will submit using ajax.

To create a ajax form we will use normal $form->create method of cakephp’s form helper.

Quite self-explanatory, just one thing i added manually is form id. If i had skipped passing value to id it would have been generated automatically, something like “User/Login” which i don’t like (and so would javascript perhaps), so i added my own id that is “loginForm”.

Now lets have a look at the (javascript) jQuery code which we use to post this form and get results.

ajaxForm() is the main submit method/function of ajax form plugin. It simply catches the onsubmit event and processes the form.

And finally here is the controller action to perform login action:

The function is self-explanatory just a few notes. “$this->autoRender prevents” rendering of view file. (I prevent it here because i output the response message inside the login action itself). Configure::write(‘debug’, 0) prevents any extra debug output so “Success” means “Success” and not “Success<!–0.3444 –> more debug output possible here including mysql queries dump etc“. I hope that makes sense. (Check how to disable debug output automatically for all ajax calls in cakephp.

I hope this helps someone.

5 thoughts on “Creating Ajax form in Cakephp using jQuery

  1. This tut is worth nothing. because there is no info how to include helper, you already have to be familiar with cakephp to even use this tut.

Leave a Reply

Your email address will not be published. Required fields are marked *