How to do Ajax in Codeigniter

Today we are going to discuss how you can integrate AJAX using jQuery’s Form Plugin in your CodeIgniter project.

When I first began developing for CodeIgniter, I was left scratching my head understanding methods that made the process easy and within CodeIgniter best practices. I find it strange that there is not much information about how to integrate AJAX into it, since it is a relatively known framework and AJAX methodology is very common in web development.

I have been looking for information about this subject on the Internet and the truth is that, besides being very scattered, it is not very clear, so here is my contribution from what I have learned, hopefully developers out there will find this tutorial useful.

Step 1

In your header template file, include the following scripts:

1
2
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

Feel free to use other AJAX methods, but for this tutorial we are going to use the jQuery form plugin

Step 2

Let’s create a form where we will be doing AJAX
Create a view file named “add.php”, then add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<h1>New Blog</h1>

<!-- This is where we will be outputting response from our AJAX requests -->
<div class = "new-blog-messages"></div>
<div class = "col-md-6">
        <!-- Generate the form attribute and add a class which we will be using to identify the form when we do AJAX -->
        <?php echo form_open('blog/add_submit', array('class' => 'new-blog-form')) ?>

        <div class = "form-group">
            <label for="title">Title</label>
            <input type="input" name="post_title" class = "form-control post_title" /><br />
        </div>
       
        <div class = "form-group">
            <label for="text">Description</label>
            <textarea name="post_content" class = "form-control post_content" rows = "15"></textarea><br />
        </div>
       
        <div class = "form-group">
            <label for="text">Short Description</label>
            <textarea name="post_excerpt" class = "form-control post_excerpt" rows = "7"></textarea><br />
        </div>
       
        <input type="submit" name="submit" value="Submit" class = "btn btn-primary new-blog-submit" />
    </form>
   
    <script>                   
    jQuery(document).ready(function($) {
       
        var options = {
            beforeSend: function(){
                $(".new-blog-messages").html('<p><img src = "<?php echo base_url() ?>images/loading.gif" class = "loader" /></p>');
            },
            complete: function(response){
                if(response.responseText === 'success'){
                    $(".new-blog-messages").html('<p class = "bg-success">Blog successfully created!</p>');
                } else {
                    $(".new-blog-messages").html('<p class = "bg-danger">' + response.responseText + '</p>');
                }
            }
        };     
        $(".new-blog-form").ajaxForm(options); 

        return false;
       
    });
    </script>
   
</div>

The above code shows the implementation of the ajax form plugin using the ajaxForm function:

1
$(".new-blog-form").ajaxForm(options);

The form is submitted to the action url: http://youwebsite.com/blog/add_submit, where the add_submit is the name of the method in your controller file found in step 3.

Step 3

Create a controller named “blog.php” then add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
class Blog extends CI_Controller {

    public function __construct() {
       
        parent::__construct();
   
    }
   
    public function index() {
       
        $data['post_title'] = 'New Blog Item';

        // Load the add.php page
        $this->load->view('templates/header', $data);
        $this->load->view('pages/blog/add');
        $this->load->view('templates/footer');
       
    }
   
    public function add_submit() {
       
        $post_content = $this->input->post('post_content');
        $post_title = $this->input->post('post_title');
        $post_excerpt = $this->input->post('post_excerpt');

        // Validate input fields
        if(empty($post_title)){
            echo 'Title can not be empty';
           
        } else if(empty($post_content)) {
            echo 'Description can not be empty';
           
        } else {
        // Replace this area with your INSERT POST function
            $args = array(
                'post_content'      =>  $post_content,
                'post_title'        =>  $post_title,
                'post_excerpt'      =>  $post_excerpt
            );
           
            $post_id = $this->post_model->insert_post($args);
           
            if($post_id) {
                echo 'success';
               
            } else {
                echo 'Failed to create new blog, please try again later.';
               
            }
        }
       
        exit();
           
    }
}

Kudos on a job well done! You have learned and achieved seamless communication through Ajax. In many cases, the code to do so was quite small. Now, you might enjoy the challenge of further enhancing the application by implementing any other UI ideas that you may have had while reading this tutorial.



Do you need help with a project? or have a new project in mind that you need help with?

Contact Me