0

I want to create a registration form where I want to use jquery and also the CI validation library. How can I do this? Upon submitting the form, I want the control to go to the validation library using jquery and return the response. Then, if all is well, I want the "form is submitted" message to be displayed on that page itself.

Edit:

here are my codes.

VIEW

<?php $this->load->view('template/header'); ?>
<div id="add_form">
    <h2>Add New Category</h2>

    <?php echo form_open('abc/abc_category_controller/add_new_category'); ?>

    <?php

    $category_data = array(
        'name' => 'category_name',
        'id' => 'category_name',
        'value' => set_value('category_name'),
        'maxlength'   => '15'
    );

    $unit_data = array(
        'name' => 'unit',
        'id' => 'unit',
        'value' => set_value('unit'),
        'maxlength'   => '10'
    );

    ?>

    <p><label for="name">Name: </label><?php echo form_input($category_data); ?></p>

    <p><label for="unit">Unit: </label><?php echo form_input($unit_data); ?></p>

    <p><?php echo form_submit('submit', 'Submit','id="submit"'); ?></p>

    <?php echo form_close(); ?>

    <?php echo validation_errors('<p class="error">'); ?>

</div><!--end add new category-form-->

<div id="success_msg">


</div>



<?php $this->load->view('template/footer') ?>

Controller- add_new_category

<?php

    class Stocks_category_controller extends CI_Controller{

    function add_new_category()
    {
        //$this->load->helper('form');
        $this->load->library('form_validation');

        $data['title'] = 'Add a new category';

        $this->form_validation->set_rules('category_name', 'Category Name', 'required');
        $this->form_validation->set_rules('unit', 'Unit', 'required');

        if ($this->form_validation->run() === FALSE)
        {
              $this->load->view('abc/add_new_category');


        }

        else
        {
            $category_name = $this->input->post('category_name');

            $unit = $this->input->post('unit');

            $this->load->model('abc/abc_category_model');

            $insert_id=$this->abc_category_model->add_new_category($category_name
                                ,$unit);


            if($insert_id!=NULL)
            {
              $this->load->view('template/success',$data);
            }

            else{
                $data['error_msg']='Error Occurred';
                $this->load->view('template/template',$data);
            }

        }

    }

    function success(){
        $data['success_msg']='New Category Successfully Created';
        $this->load->view('template/success',$data);
    }
  }

And finally the model.

   function add_new_category($category_name,$unit){

      $data = array(
           'abc_category_name' => $category_name ,
           'unit' => $unit
        );

        $this->db->insert('abc_category', $data); 
        $insert_id=$this->db->insert_id();

        return $insert_id;
   }

}

What I want is that when I submit the form, jquery validation should take place. And if, all is well then the SUccessful message be displayed using ajax only and page should not reload. Also, please tell me is it possible to use jquery validation and CI validation library both and maintaining ajax at the same time?

3
  • What have you tried? Commented Jun 16, 2012 at 6:32
  • @sczizzo- I have just created the form and the validator. I dont know how to proceed with the jquery thing. Commented Jun 16, 2012 at 6:49
  • You'll have to post some code or something. We can't help you proceed if we don't know what you've got. Commented Jun 16, 2012 at 6:51

2 Answers 2

5

To implement both client side and server side validations you need to use the jquery validation plugin.

So, you need to include:

  1. jQuery javascript library

  2. jQuery validation plugin

Load the javascript with

<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>

then setup your form:

$attr = array('id' => 'demo_form');
echo form_open('demo/validation_example', $attributes);

and validate your form like:

$(document).ready(function() {
  $("#demo_form").validate({
    rules: {
            name: {
                required: true
            },
            ...
    },
    messages: {
             name: {
                required: "Name required",
            },
    },
    errorElement: "span",
        errorPlacement: function(error, element) {
                error.appendTo(element.parent());
        }

  });
});

And use the server side validation too, because it is not a good practice to use only client side validation.

For more help, you can find a good tutorial about

how to implement the jquery validation with codeigniter

and working demo

Where you can check jquery validation, and by disabling the javascript of your browser, you can check codeigniter server side validations done with php.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer buddy. But I have a problem with that code i.e. on successfull submission of the page, upon reloading the page, the data will be sent again. I know how to avoid this problem, but I just wanted to use ajax for this so that this problem will be solved automatically.
@sanjay, Can you share the proper link because pages redirect on some gaming page
1

I think you have to use jquery ajax for this.

First you need to post your data. Set your submit button to fire jquery ajax like this.

 $.ajax({
        type: "GET",
        url: "/controller/validate",  //your controller action handler
        dataType: "json",
        data: {name:value, name: value}, //set your post data here
        cache:false,
        success: function(data){
             //handle the callback response 
             if(data.success)
                alert("Success");
             else
                alert(data.errors);
       }
 });

Next in your controller action, validate your post data using codeigniter validator. If it fails the validation, you need to send the errors back to your js callback function using json_encode in your view. Set the data error like this, In your view (the view you will set for /controller/validate), do something like this

$data['errors'] = validation_errors();
echo json_encode($data);

You will have the errors back to you without refreshing the page. When the validation is success, just set a $data['success'] and use echo json_encode using if statement so that only success data will be retrieved. I have set the ajax script callback.

5 Comments

In addition, you can use client side validation suggested by @Sanjay above. Its true you have to strongly implement the server side validation. From my suggestion above, you do already
I didnt get what do I need to write in if($this->form_validation->run() === FALSE){ //here } And please elaborate what do I need to add in my view. PS: I am not well-versed with ajax.Kindly bear with me. –
There's no need for you to write there in between. Just this, you have to set a view for /controller/validate and in that view, do this, $data['errors'] = validation_errors(); echo json_encode($data) . View Code: if(!empty(validation_errors()) { $data['errors'] = validation_errors(); $data['success'] = false; }//check if validation_errors has values else $data['success'] = true; echo json_encode($data); Automatically, you will get a json data in your js.
Please have a look at my updated view. tinypaste.com/396a58bf Please suggest me how do I proceed with this.
make a separate view for your submit handler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.