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 http://jquery.malsup.com/form/ 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:
< ?php
echo $javascript->link('jquery-1.3.2.min.js'); //main jQuery library
echo $javascript->link('jquery.form.js'); //ajax form plugin
?>
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.
< ?php echo $form->create('User', array('action' => 'login', 'id'=>'loginForm')); echo $form->text('User.username'); echo $form->password('User.password'); echo $form->submit('Login'); echo $form->end(); echo ' '; //field to be populated by possible error message ?>
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.
var options = {
target: '#formUpdateID', // target element(s) to be updated with server response (could be hidden initially)
beforeSubmit: function(formData, jqForm, options) { // pre-submit callback
//perform some validations etc.
//"return false" would stop the form submit
//for example
if($('#UserUsername').val()=="") {
alert("Please enter username");
$('#UserUsername').focus();
return false;
}
//check auther's site for more details on arguments formData, jqForm, options etc.
},
success: function (responseText, statusText, xhr, $form) {
if(responseText=="Success") {
//replcing entire form contents with a message
$('#formUpdateID').html("Login success, Redirect to profile page etc.");
//redirect now etc..etc..
} else {
//error! do some alert or display message nicely, like
alert("There was some error while logging in. Please try again.");
//or
$('.error-message').html(responseText);
//assuming that our responseText will have some error message
//(see controller action below)
}
}
}
$('#loginForm').ajaxForm(options); //track and wait for a onsubmit event on "logiForm"
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:
function login() {
$this->autoRender = false; //will prevent render of view
Configure::write('debug', 0); //it will avoid any extra output
if(!empty($this->data)) {
$found = $this->User->find('count', array('conditions'=>array('username'=>$this->data['User']['username'], 'password'=>$this->data['User']['password'])));
if($found) { //user found
echo "Success";
//this output becomes responseText for ajax function
} else {
echo "Incorrec username and/or password. Please try again";
//this output becomes responseText for ajax function
}
}
}
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 http://www.devarticles.in/cakephp/disable-cakephp-debug-output-when-using-ajax/ how to disable debug output automatically for all ajax calls in cakephp.
I hope this helps someone.
Possibly Related posts:
- Creating Ajax form in Cakephp (with Prototype.js)
(If you are using jQuery with cakephp you may want to view this article, Creating Ajax form in Cakephp using jQuery ) With the help... - Limitation on the number of characters in jquery ajax response
The following jquery ajax call would return approx. 8442 characters in its “html” response. Content exceeding this number would be truncated. var url = "load_pocket_fabrics.php?filter="... - Form DOM element not recognized (created) in ajax form in IE when placed with end tag missing
Skipping a form end tag </form> costed me almost a day (i had to go to bed abandoning the fixing for some time though;)). I... - Fix to jQuery plugin does not work on ajax loaded content
I had been loading table records through ajax pagination using jquery. Some of the urls/links (View Details, Edit and Delete) in loaded content had been... - Disable CakePHP debug output when using Ajax
While developing a CakePHP application and debug value set to greater than 0(zero) (development mode) we may want to show our Ajax results clean i.e....
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.






This was helpful. It contained all the details that I needed.
Thanks
hello. gud article. although lacking to provide full details. Keep it up. Thanks..