info@ektanjali.com +91 99276-99286

CakePHP 2.x User Management Premium Plugin Version 2.3.x

Ajax Form Validations

I have developed a form validations element for validating form fields by ajax.

How to use Ajax Form Validations in Cake Php
1. If you are using Security component then your controller's before filter should look like-

public function beforeFilter() {
    parent::beforeFilter();
    if(isset($this->Security) &&  $this->RequestHandler->isAjax()){
        $this->Security->csrfCheck = false;
        $this->Security->validatePost = false;
    }
}


2. Now in controller's function ajax handling for e.g. in addUser function of users controller

if($this->RequestHandler->isAjax()) {
    configure::write('debug', 0);
    $this->layout = 'ajax';     // uses an empty layout
    $this->autoRender = false;  // renders nothing by default
}

$this->User->set($this->data);
$UserRegisterValidate = $this->User->RegisterValidate();    // call validate function of model
if($this->RequestHandler->isAjax()) {
    if ($UserRegisterValidate) {
        $response = array('error' => 0, 'message' => 'success');
        return json_encode($response);
    } else {
        $response = array('error' => 1,'message' => 'failure');
        $response['data']['User']   = $this->User->validationErrors;
        return json_encode($response);
    }
} else {
    if ($UserRegisterValidate) {
        // rest code here
    }



3. Include ajax pagination js in View file

<?php echo $this->Html->script('/usermgmt/js/ajaxValidation'); ?>

4. Now in View file you should add ajax_validation element in following way for e.g. in add_user.ctp

<?php echo $this->element('Usermgmt.ajax_validation', array("formId" => "addUserForm""submitButtonId" => "addUserSubmitBtn")); ?>

where
'ajax_validation' is a ajax validation element, location is yourapp/app/Plugin/Usermgmt/View/Elements/ajax_validation.ctp.
"formId" is your form id where you want to add ajax validations.
"submitButtonId" is your form submit button id.

5. Now in View don't forget to add form id and submit button id

<?php echo $this->Form->create('User', array('action' => 'addUser''id'=>'addUserForm')); ?>
<?php echo $this->Form->Submit(__('Add User'), array('id'=>'addUserSubmitBtn'));?>

For more information see
Users Controller yourapp/app/Plugin/Usermgmt/Controller/UsersController.php
Add User View yourapp/app/Plugin/Usermgmt/View/Users/add_user.ctp
Ajax Validation Element yourapp/app/Plugin/Usermgmt/View/Elements/ajax_validation.ctp
Ajax Validation Js yourapp/app/Plugin/Usermgmt/webroot/js/ajaxValidation.js