CakePHP and JQuery ( 2 )
20 Aug 2010 Add Comments Beginner Level This is the second part of CakePHP and JQuery series. If you are not familiar with setting up JQuery in CakePHP, pleaser read our first article at CakePHP and JQuery ( 1 ).
In this tutorial, we will teach how to use JQuery in CakePHP to do ajax save.
The final task is to save a record through Ajax using JQuery.
Table Of Content
Content
1.Preparation 
-
Set up JQuery in CakePHP according to part 1 of the series.
-
Create a simple database table:
CREATE TABLE `tutors` ( `id` int(11) NOT NULL auto_increment, `name` varchar(250) collate latin1_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=6 ;
-
Give correct database information at app/config/database.php and make sure that CakePHP is able to connect to your database.
-
Create "app/controllers/tutors_controller.php", take note we included RequestHandler here because we need it later to detect ajax request:
<?php class TutorsController extends AppController { public $name = 'Tutors'; public $components = array('RequestHandler'); public function index(){ $this->layout='default'; } } ?> -
Create a view file "app/views/tutors/index.ctp".
2.Set up view file
Setting up view is very straightforward, what we need to do is simply create a form using CakePHP form helper, assign the form an unique id and point its action to "/tutors/add", open "app/views/tutors/index.ctp" and add codes below:
<?php
echo $form->create('Tutor',array('action'=>'add','id'=>'saveForm'));
echo $form->input('name');
echo $form->submit('Save');
echo $form->end();
?>
3.Set up controller action 
At step 2, we have point the form action to "tutors/add", so we need to set up the controller action for it here. Open "app/controllers/tutors_controller.php", and add function add() as below. Firstly, we set autoRender to false, because we don't need a view for this action. Then we detect if it is an ajax request using RequestHandler, if so, we set debug to 0, so CakePHP will not append any message to it even you turn debug level higher than 0 from global config. At last, we save the record by calling model function, and output status string.
public function add(){
$this->autoRender=false;
if($this->RequestHandler->isAjax()){
Configure::write('debug', 0);
}
if(!empty($this->data)){
if($this->Tutor->save($this->data)){
echo 'Record has been added';
}else{
echo 'Error while adding record';
}
}
}
4.Set up JQuery ajax call
Finally we come to use JQuery to do ajax submit from view to controller, we have decided to put JQuery codes in layout file, just to make it easier to organize. Open "app/views/layouts/default.ctp", and add JQuery codes inside header section of the document as below. What we did here is, firstly we serialize the form data and get form action url. Then we call $.ajax() function to do the magic.
<header>
***other codes ****
<script type="text/javascript">
$(document).ready(function () {
$('#saveForm').submit(function(){
//serialize form data
var formData = $(this).serialize();
//get form action
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(data,textStatus,xhr){
alert(data);
},
error: function(xhr,textStatus,error){
alert(textStatus);
}
});
return false;
});
});
</script>
***other codes ****
</header>
5.Final codes 
Completed codes for view, controller and layout:
"app/views/tutors/index.ctp"
<?php
echo $form->create('Tutor',array('action'=>'add','id'=>'saveForm'));
echo $form->input('name');
echo $form->submit('Save');
echo $form->end();
?>
"app/controllers/tutors_controller.php"
<?php
class TutorsController extends AppController {
public $name = 'Tutors';
public $components = array('RequestHandler');
public function index(){
$this->layout='default';
}
public function add(){
$this->autoRender=false;
if($this->RequestHandler->isAjax()){
Configure::write('debug', 0);
}
if(!empty($this->data)){
if($this->Tutor->save($this->data)){
echo 'Record has been added';
}else{
echo 'Error while adding record';
}
}
}
}
?>
"app/views/layouts/default.ctp"
<html>
<head>
<?php echo $html->charset(); ?>
<!-- scripts -->
<?php echo $javascript->link('jquery-1.4.2.min'); ?>
<!-- document javascripts -->
<script type="text/javascript">
$(document).ready(function () {
$('#saveForm').submit(function(){
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(data,textStatus,xhr){
alert(data);
},
error: function(xhr,textStatus,error){
alert(textStatus);
}
});
return false;
});
});
</script>
</head>
<body>
<?php echo $content_for_layout; ?>
</body>
</html>
The end 
If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.



16 Comments
I'm in the process of going from being a DBA to Web Developer. This article is something that I've needed to see for quite a while, specifically CakePHP, jQuery, and Ajax all working together.
The Ajax save is working properly as far as the record gets saved, but Google Chrome is not refreshing the part of the page that displays my newly-added comment. Also the input box isn't cleared after clicking 'Add Comment' (using posts and comments instead of Tutorials). I am using the RequestHandler component and have jQuery and everything else set up correctly I do believe.
What we did in this tutorial is to post data to the backend an save it to Database. Ajax is handling the data posting part.
To refresh the data, you will have to either reload the page or retrieve the data using Ajax again.
The Ajax save is working properly as far as the record gets saved, but Google Chrome is not refreshing the part of the page that displays my newly-added comment. Also the input box isn't cleared after clicking 'Add Comment' (using posts and comments instead of Tutorials). I am using the RequestHandler component and have jQuery and everything else set up correctly I do believe
@Party Dresses
You need to manually refresh the page, current code wont refresh the page after ajax
Hey, bro. nice tuts although I stuck on one stone. After serializing form data and posting it to controller action through jQuery it is saving to the database table allright but it is storing as NULL value there. I reckon it is causing because of serializing. So, boss can you help you out to resolve this ? Thank you again for saving a lot of time by giving this wonderful tut. Waiting to get your reply. :-)
@tushersuvro
What the issue of the serilize data?
hi, new to the site, thanks.
The echo statements in the controller render on a white page. I don't go back to the page that had my form in it that made the ajax request. The good news is the data is getting into the database. Help!
@David Marks
The echo statements in the controller should not render a page.
And you need to manually refresh the page in order to get the inserted data.
thank for great tutorial
i'm newbie in cake
the article help me to understand convention
of cakephp
before to read your article
i try to write php ajax code in cake php
i don't know to use php code complatible with cake code
thank
taqman
CakePHP is just a PHP framework.
You normal php code will work in CakePHP in most cases.
I have problem http://upic.me/show/26102468
this code http://bin.cakephp.org/view/618610989
can you help to modified this
Great help, thanks very much!
Sorry...
the autorender not working,
i stil go to add page, add page stil viewed...
but the date is saved, but if i move the save code into "requestHandler", the data wan't save...
need help...
thank you...
Please check the javascript error using Firebug or any web developer tool.It seems like there is a JS error in your case
Thanks for the code - learning cakePhp and now I can add in my favorite tool, jQuery. Onward!