Category Covered

how to validate cakephp form using jquery

 

To validate cakephp form using jquery follow the most easiest step using jquery validation.

Add jquery to your default or any layout for that page

For example here is the cakephp function that you want to validate by jquery on both client and server side

 

    function add() {
        if($this->data['Enquiry']['form_submit']=='yes'){
            $this->layout="ajax";
        }else{
            $this->layout="default";
        }
        if (!empty($this->data)) {
            $this->Enquiry->create();
            if ($this->Enquiry->save($this->data)) {
                $this->Session->setFlash(__('Your enquiry has been saved', true));
                //$this->redirect(array('controller' => 'contents', 'action' => 'lists'));
            } else {
                $this->Session->setFlash(__('Your enquiry could not be saved. Please, try again.', true));
            }
        }
    }

 

Make sure that you have a layout for ajax. Here i have used a layout ajax.ctp

Here is the views page named "add.ctp" which content the HTML and javascript

<script type="text/javascript">
$(document).ready(function () {
    $(".submit").bind("click", function (event) {
        event.preventDefault();
        $(".submit").html('Sending...');
        $.ajax({
            data: $(".submit").closest("form").serialize(),
            dataType:"html",
            success:function (data, textStatus) {
                $(".MidClass").html(data);
               
            },
            type:"post",
            url:$(".submit").closest("form").attr('action'),
        });
    });
});
</script>


<div class="enquiries_front">
    <?php echo $this->Session->flash();
    echo $this->Session->flash('auth');    ?>
<?php echo $this->Form->create('Enquiry');?>
    <fieldset>
        <legend><?php __('Add Enquiry'); ?></legend>
    <?php
        echo $this->Form->input('customer_name', array('label'=>'Your name'));
        echo $this->Form->input('form_submit', array("type"=>"hidden", 'default'=>'yes'));
        echo $this->Form->input('subject');
        echo $this->Form->input('email');
        echo $this->Form->input('message');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>

 
Comments on "how to validate cakephp form using jquery"
Comment by, Talaman

Thanks! very simple article and work at first! blesses!
Related posts