TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

CakePHP and JQuery ( 2 )

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.

Preparation

  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".

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(); 
?>

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

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>

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.