Sending forms with AJAX in CodeIgniter

Today we are going to explain how we can send a form via AJAX using jQuery in CodeIgniter, so we avoid to reload the whole page, giving the appearance of “desktop application” to our web application, being able to perform certain actions without reloading the entire page view.

Creating the form

First, we need to create our form. In this case we will create a generic form, where we will add different types of fields to make the example as complete as possible, but functionally not very helpful, mainly for teaching purposes… So in our view file in CodeIgniter we add the following code:

$attr = 'id="my_form"'; //The form will have the id 'my_form'
 echo form_open('my_controller/process_form',$attr);
 //Create a text field
 echo form_label('Field1: ','field1');
 $data = array(
 'name'        => 'field1',
 'id'          => 'field1',
 'value'       => ''
 );
 echo form_input($data);
 //Create some checkboxes
 $data = array(
 'name'        => 'field2',
 'id'          => 'field2',
 'value'       => '2',
 'checked'     => false
 );
 echo form_checkbox($data);
 $data = array(
 'name'        => 'field3',
 'id'          => 'field3',
 'value'       => '3',
 'checked'     => false
 );
 echo form_checkbox($data);
 //Create some radio
 $data = array(
 'name'        => 'radio',
 'id'          => 'radio1',
 'value'       => 'radio1',
 'checked'     => false
 );
 echo form_radio($data);
 $data = array(
 'name'        => 'radio',
 'id'          => 'radio2',
 'value'       => 'radio2',
 'checked'     => false
 );
 echo form_radio($data);
 //And a textarea
 echo form_label('Textarea: ','textarea');
 $data = array(
 'name'        => 'textarea',
 'id'          => 'textarea',
 'value'       => '',
 'rows'        => '2',
 'cols'        => '50' );
 echo form_textarea($data);
echo form_close();

The controller

This is where comes the most important and, for me, also the most interesting part of the whole process. In our controller we will identify wether the form was sent by AJAX or by the traditional way (reloading page). So that, we will be able to load some views or anothers without having two functions in our controller for the same task. The important thing is to examine the PHP global variable $_SERVER with an item called “HTTP_X_REQUESTED_WITH”, which indicates whether the request was made via AJAX or using a standard HTTP request. So that, our controller code would be:

<?php

//Store into the constant 'IS_AJAX' whether the request was made via AJAX or not
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
class My_controller()
{
    public function process_form()
    {
        //Load library form_validation
        $this->load->library('form_validation');

        //Set some validation rules
        $this->form_validation->set_rules('Field1','required|xss_clean');
        $this->form->validation->set_rules('Textarea','required|xss_clean');

        if($this->form_validation->run())
        {
            //Do whatever is needed to process the form and store the data
            ...

            $data['no_error'] = $this->processing_tasks();
            if(IS_AJAX)
            {
                $this->load->view('ajax_response',$data['no_error']);
            }
            else
            {
                //Load standard view
            }
        }
        else
        {
            //The form is not valid
            if(IS_AJAX)
            {
                $data['message'] = validation_errors();
                $this->load->view('ajax_no_valid',$data);
            }
            else
            {
                //Load standard view
            }
        }
    }
}

For this, we assume that we have the files ajax_response.php and ajax_no_valid.php in the “views” directory of our application with the following content:

<?php
//ajax_response.php
if($no_error)
{
    echo "The for was processed successfully!";
}
else
{
    echo "Ooopss! There was some problem trying to process the form";
}
?>

<?php
//ajax_no_valid.php
echo $message;

And now… jQuery

Now we just need to include the JavaScript code that will send the form’s content via AJAX, preventing the entire page reload:

$(function(){
    $('#my_form').submit(function(evnt){
        evnt.preventDefault(); //Avoid that the event 'submit' continues with its normal execution, so that, we avoid to reload the whole page
        $.post(url+"my_controller/process_form", //The variable 'url' must store the base_url() of our application
        $("form#my_form").serialize(), //Serialize all the content of our form to URL format
        function (data) {
            $('div#sending_form').prepend(data); //Add the AJAX response to some div that is going to show the message
        });
    });
});

In our jQuery code, we use the function serialize(), which takes care of encoding all form fields in URL format (a=1&b=2&c=3…) and sparing us having to do it by ourselves one by one. It is remarkable that serialize() does not encode those fields that do not have the attribute name, nor serializes the fields like <input type=”file” />. Here you have more information about the function serialize() (http://api.jquery.com/serialize/).

Well, with this you already can send forms via AJAX using jQuery in CodeIgniter.

Leave a Reply

Your email address will not be published. Required fields are marked *