Oct 9, 2014

Ketan Patel

Ajax Call Validation in CakePHP

ajax call validation in cakephp



For any application, validation of user input is very important job. By doing so we make sure that the data in a model conforms to the business rules defined for the application. Simple examples for such validation rules can be email, alphanumeric, min-max value etc.

In this tutorial we're going to learn how to validate the ajax call in CakePHP. This post assumes that you know the basics of model validation rules.If not then i would suggest you to follow our Cakephp Tutorial Series to make the concept clear.


Note: The CakePHP version used in this tutorial is : 2.5.2


Create the Sample Table

Simply run the SQL query given below into your DB:


CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(50),
    lastname VARCHAR(50),
    email VARCHAR(150),
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);


Creating the Controller


Create a file called 'UsersController.php' in your app/Controller directory and copy the code given below.


<?php 

class UsersController extends AppController {
    var $helpers = array('Html', 'Form');
    
  public function index() {
        $this->set('users', $this->User->find('all'));
    }

 public function ajax_call() {
        if ($this->request->is('ajax')) {
            if (!empty($this->data)) {
                $this->User->create();
                $this->User->set($this->data['User']);
                if($this->User->validates()) {
                      if ($this->User->save($this->data)) {
                      $response=array();
                      $response['status']='success';
                      $response['message']='The User has been saved.';
                      $response['data']=$this->data;
                      echo json_encode($response);
                      die;
                    }
                }
               else {
                    $response=array();
                    $User = $this->User->invalidFields();
                    $response['status']='error';
                    $response['message']='The User could not be saved. Please, try again.';
                    $response['data']=compact('User');
                    echo json_encode($response);
                    die;
                }
            }
        }
    }
    
    public function add(){
     $this->render('edit');
    }
    
    
 public function edit($id = null) {
     if (!$id) {
         throw new NotFoundException(__('Invalid user'));
     }
     $user = $this->User->findById($id);
     if (!$user) {
         throw new NotFoundException(__('Invalid user'));
     }
     if (!$this->request->data) {
         $this->request->data = $user;
     }
  }
}

?>



Explanation  


(1) function index()  : This function will display all the records of the users.
(2) function add()     : For this function we are rendering the view of edit action.
(3) function edit()     : It will pre populate the details of the user being edited.
(4) function ajax_call() : This is the main function we're dealing in this demo.This function will be called for both the actions add and edit.
- One method is used in this function which is "invalidFields()". This method returns all the invalid fields after a validates().
- Based on the result, we are sending the response by json encoding.



Creating the Model rules.


Create on file called 'User.php' in your app/Model directory. Paste the code given below. You can have any numbers or any types of rules as per your requirements as shown in the example.

<?php 
class User extends AppModel {
        public $validate = array(
                 'firstname' => array(
                      'rule' => 'notEmpty',
                      'message'=>'Please fill the firstname'
                  ),
                'lastname' => array(
                    'rule1'=>array(
                            'rule' => 'notEmpty',
                             'message'=>'Please fill the lastname'
                      ),
                  'rule2'=>array(
                            'rule' => 'alphaNumeric',
                            'message'=>'Please enter only characters'
                    )          
              ),
             'email' => array(
                  'rule' => 'email',
                  'message'=>'Please enter correct Email address'
         )
    );
}
?>

Creating the View


We are going to create only one view file called "edit.ctp". For the add action also we will render this view.
Create a folder called 'Users' in your app/views directory.Now make one file called edit.ctp in that folder.
-  Copy the below code in edit.ctp file.


edit.ctp file


<h1>
<?php
$action = ($this->action == 'add') ? 'Add User' : 'Edit User';
  echo $action;
?>
</h1>
<div class="users form">
      <p class="msg"></p>
      <?php
          echo $this->Html->script('users_edit');
          echo $this->Form->create('User',array('novalidate'=>true));
          echo $this->Form->input('firstname');
          echo $this->Form->input('lastname');
          echo $this->Form->input('email');
          echo $this->Form->input('id', array('type' => 'hidden'));
       ?>
    <?php echo $this->Html->image('loading.gif', array('alt' => 'Loading...')); ?>
</div>
   <?php 
     $options = array
     (
         'label' => 'Save',
         'value' => 'Save',
         'id' => 'save'
     );
     echo $this->Form->end($options);?>
</div>



index.ctp

Now create one file called 'index.ctp' in the same folder.Copy the content below and paste in it.
<h1>Users List</h1>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Action</th>
    </tr>
    <!-- looping through $users array,display user details -->
    <?php foreach ($users as $user): ?>
    <tr>
        <td><?php echo $user['User']['id']; ?></td>
        <td><?php echo $user['User']['firstname']; ?></td>
        <td><?php echo $user['User']['lastname']; ?></td>
        <td><?php echo $user['User']['email']; ?></td>
        <td><?php echo $this->Html->link('Edit',array('action'=>'edit',$user['User']['id'])); ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($user); ?>
</table>


Javascript


-  Create one file called 'users_edit.js' in your app/webroot/js directory.
-  Make sure you have included jquery file.

$(document).ready(function(){
 $('#UserAddForm, #UserEditForm').submit(function(){ 
   var fid=$('form').attr('id');
   var formData = $('#'+fid).serialize();
   event.preventDefault();
    $.ajax({
     type : 'POST',
     url : '/cakephp5/users/ajax_call',
     data: formData,
      beforeSend: function()
           {
      $('#save').val('Saving...');
      $('#save').attr('disabled', true);
      $(".error-message").remove();
           
           },
    success : function(response) {
     
     var response1=jQuery.parseJSON(response);
      $('#save').attr('disabled', false);
           if(response1.status=='success'){
           $('#save').val('Save');
           window.setTimeout(function() {
              $(".message").fadeOut('slow');
              $(".msg").text(response1.message);
              window.location = '/cakephp5/users';
             }, 2000);
           }
           else if(response1.status=='error'){
            $('#save').attr('disabled', false);
            $('#save').val('Save');
            $(".msg").text(response1.message);
            $.each(response1.data, function(model, errors) {
                for (fieldName in this) {
                    var element = $("#" + camelcase(model + '_' + fieldName));
                    var create = $(document.createElement('div')).insertAfter(element);
                    create.addClass('error-message').text(this[fieldName][0])
                }
            });
            
           }
    },
    error : function() {
           
    }
   });
  
 });
 

    function camelcase(inputstring) {
        var a = inputstring.split('_'), i;
        s = [];
        for (i=0; i<a.length; i++){
            s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
        }
        s = s.join('');
        return s;
    }

});



Explanation:



On the submit event of both forms (add and edit) having ids #UserAddForm and #UserEditForm respectively we are calling the ajax_call method.

$('#UserAddForm, #UserEditForm').submit(function(){}

On success we are redirecting to the index page.

window.setTimeout(function() { 
     $(".message").fadeOut('slow');
     $(".msg").text(response1.message);
     window.location = '/cakephp5/users';
   }, 2000);


On error, for each invalidFields we are creating error messages.

$.each(response1.data, function(model, errors) {
         for (fieldName in this) {
             var element = $("#" + camelcase(model + '_' + fieldName));
             var create = $(document.createElement('div')).insertAfter(element);
             create.addClass('error-message').text(this[fieldName][0])
        }
});


camelcase function will simply returns the field's name camelcase.
function camelcase(inputstring) {
        var a = inputstring.split('_'), i;
        s = [];
        for (i=0; i<a.length; i++){
            s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
        }
        s = s.join('');
        return s;
}






That's it.!! you're done with Ajax call validation in CakePHP.Hope you understand the concept.

If you like this post then please do share to spread this to the world.


Ketan Patel

About Ketan Patel -

I have developed a wide range of websites using CorePHP, Opencart, CakePHP and CodeIgniter including sites for startup companies and small businesses. Apart from my blogging life, I like to read Novels, Listening music and Net surfing.

Subscribe to this Blog via Email :