Hi friends,

I'm wondering what is the best way to go about validating my forms with both php and ajax.

For example, I want to use the form_validation library but also jquery such that the page doesn't require a refresh or redirect.

How best to do this what is best practice?

This question also extends to using jquery in general with codeigniter...

I usally break up the process when using ajax in CI. This example is a login form. The methods are placed in the login controller.

Form View:

public function index()
    $this->load->viewA('login', $data);

Form Processor:

public function login_processor()

    $this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');

    if($this->form_validation->run() == false){
        $errors = validation_errors();
        echo json_encode($errors);
        //login user
        $logged_in = $this->login_model->login($this->input->post('username', true), $this->input->post('password', true));

        if($logged_in == true){
            echo json_encode(array('success' => 'Loggin successful!'));
            echo json_encode(array('error' => 'Invalid username or password'));


This hasn't been tested, I just wanted to show you the process of how I go about using ajax.

Thanks... Solved it.


function submit() 

    $this->form_validation->set_rules('name', 'course_code', 'trim|xss_clean|required');
    $this->form_validation->set_rules('email', 'name', 'xss_clean|min_length[8]|required');
    // .. etc           
    if ($this->form_validation->run() == TRUE) 




<div id="contact_form">

    <h1>Contact Us!</h1>

    echo form_open('contact/submit');
    echo form_input('name', 'Name', 'id="name"');
    echo form_input('email', 'Email', 'id="email"');
    $data = array('name' => 'message', 'cols' => 35, 'rows' => 12);
    echo form_textarea($data, 'Message', 'id="message"');
    echo form_submit('submit', 'Submit', 'id="submit"');
    echo form_close();

<script type="text/javascript">
$('#submit').click(function() {

    var form_data = {
        name: $('#name').val(),
        email: $('#email').val(),
        message: $('#message').val()    

        url: "<?php echo site_url('contact/submit'); ?>",
        type: 'POST',
        data: form_data,
        success: function(msg) {
            if (msg == "no")
            if (msg == "yes")


    return false;