Category

Category: CodeIgniter

AJAX Multi File upload in CodeIgniter

Uploading files asynchronously can be a pain at the best of times, but when coupled with CodeIgniter, it can be a particularly frustrating experience. Gladly, there is now a very easy way to upload multiple files using jQuery Form Plugin.

I assume you have a working knowledge of CodeIgniter and jQuery, and that you already have installed and set-up CodeIgniter.

Download the Multi File Upload Extension

Download Extension for Codeiginiter version 3.0 and above:

or download support for version 2.2 and bellow

Installation: Simply copy the MY_Upload.php file to application/libraries directory.

Creating the Upload Form

Using a text editor, create a form called upload_form.php. In it, place this code and save it to your applications/views/upload folder:

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
<html>
<head>
<script type = "text/javascript" src = "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type = "text/javascript" src = "//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.js"></script>
<title>Upload Form</title>
</head>
<body>
    <!-- AJAX Response will be outputted on this DIV container -->
    <div class = "upload-image-messages"></div>

    <div class = "col-md-6">
        <!-- Generate the form using form helper function: form_open_multipart(); -->
        <?php echo form_open_multipart('upload/do_upload', array('class' => 'upload-image-form'));?>
            <input type="file" multiple = "multiple" accept = "image/*" class = "form-control" name="uploadfile[]" size="20" /><br />
            <input type="submit" name = "submit" value="Upload" class = "btn btn-primary" />
        </form>

        <script>                   
        jQuery(document).ready(function($) {

            var options = {
                beforeSend: function(){
                    // Replace this with your loading gif image
                    $(".upload-image-messages").html('<p><img src = "<?php echo base_url() ?>images/loading.gif" class = "loader" /></p>');
                },
                complete: function(response){
                    // Output AJAX response to the div container
                    $(".upload-image-messages").html(response.responseText);
                    $('html, body').animate({scrollTop: $(".upload-image-messages").offset().top-100}, 150);
                   
                }
            }; 
            // Submit the form
            $(".upload-image-form").ajaxForm(options); 

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

You’ll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you.

The Controller

Using a text editor, create a controller called upload.php. In it, place this code and save it to your applications/controllers/ folder:

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

class Upload extends CI_Controller {

    public function __construct() {
   
        parent::__construct();
        // Load the helpers
        $this->load->helper(array('form', 'url'));
    }

    public function index() {
       
        // Load the form
        $this->load->view('templates/header');
        $this->load->view('upload/upload_form', array('error' => ' ' ));
        $this->load->view('templates/footer');
       
    }
   
    /**
     * Multiple upload functionality will fallback to CodeIgniters default do_upload()
     * method so configuration is backwards compatible between do_upload() and the new do_multi_upload()
     * method provided by Multi File Upload extension.
     *
     */

    public function do_upload(){
   
        // Detect form submission.
        if($this->input->post('submit')){
       
            $path = './uploads/';
            $this->load->library('upload');
           
            /**
             * Refer to https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
             * for full argument documentation.
             *
             */

             
            // Define file rules
            $this->upload->initialize(array(
                "upload_path"       =>  $path,
                "allowed_types"     =>  "gif|jpg|png",
                "max_size"          =>  '100',
                "max_width"         =>  '1024',
                "max_height"        =>  '768'
            ));
           
            if($this->upload->do_multi_upload("uploadfile")){
               
                $data['upload_data'] = $this->upload->get_multi_upload_data();
               
                echo '<p class = "bg-success">' . count($data['upload_data']) . 'File(s) successfully uploaded.</p>';
               
            } else {   
                // Output the errors
                $errors = array('error' => $this->upload->display_errors('<p class = "bg-danger">', '</p>'));              
           
                foreach($errors as $k => $error){
                    echo $error;
                }
               
            }
           
        } else {
            echo '<p class = "bg-danger">An error occured, please try again later.</p>';
           
        }
        // Exit to avoid further execution
        exit();
    }
}

Configure Routes

Go to application/config/routes.php and add the following lines:

1
2
3
$route['upload/do_upload'] = 'upload/do_upload';
$route['upload/(:any)'] = 'upload/view/$1';
$route['upload'] = 'upload';

The Upload Folder

You’ll need a destination folder for your uploaded images. Create a folder at the root of your CodeIgniter installation called uploads and set its file permissions to 777.

Go ahead and try it!

To try your form, visit your site using a URL similar to this one:

1
example.com/index.php/upload/

Implementing AJAX Pagination with Search in CodeIgnier

ajax-pagination-with-search-in-codeigniter

In this tutorial, you will learn how to program an Ajax pagination with search functionality. We will not be using any 3rd party libraries for PHP or JavaScript to accomplish this task so that I may pass along the highest level of programming education and insight on this topic to you.

You can just copy the code below and customize the database fields to meet your requirements. I have also provided a brief documentation within the codes so that the steps are clear.

Step 1

In your application/view, create a new folder and name it “blog”. Then inside the blog folder, create a new file and name it “index.php”. Open index.php, 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
57
58
<script type = "text/javascript" src = "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>

<article class="navbar-form navbar-left">
    <div class="form-group">
        <input type="text" class="form-control blog_search_text" placeholder="Enter a keyword">
    </div>
    <input type = "submit" value = "Search" class = "btn btn-primary blog_search_submit" />
</article>

<br />

<div class="col-md-12 content">
    <script type="text/javascript">
    jQuery(document).ready(function($) {

        function cvf_load_all_posts(page){
            // Start the transition
            $(".cvf_pag_loading").fadeIn().css('background','#ccc');
           
            // Data to receive from our controller
            var data = {
                page: page,
                search: $('.blog_search_text').val()
            };
           
            // Send the data
            $.post("<?php echo base_url('blog/index_display')?>", data, function(response) {
                // If successful Append the data into our html container
                $(".cvf_universal_container").html(response);
                // End the transition
                $(".cvf_pag_loading").css({'background':'none', 'transition':'all 1s ease-out'});
            });
        }
       
        // Load page 1 as the default
        cvf_load_all_posts(1);
       
        // Handle the clicks
        $('body').on('click', '.cvf_universal_container .cvf-universal-pagination li.active', function(){
            var page = $(this).attr('p');
            cvf_load_all_posts(page);
           
        });
       
        // Search
        $('body').on('click', '.blog_search_submit', function(){
            cvf_load_all_posts(1);
        });
                   
    });
    </script>
       
    <div class = "cvf_pag_loading">
        <div class = "cvf_universal_container">
            <div class="cvf-universal-content"></div>
        </div>
    </div>
</div>

In the above code, we created a script that will send a request post to the controller file “http://yourwebsite.com/blog/index_display”. Our request post contains the page number we want to be loaded and the value of the search input field. We then output the response of our controller to the div container with a class name: “cvf_universal_container”.

Step 2

In you application/controller, create a new file and name it “blog.php”, inside blog.php, 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<?php
class Blog extends CI_Controller {

    public function __construct() {
       
        parent::__construct();
       
    }

    public function index() {
       
        $data['post_title'] = 'Blog';
       
        $this->load->view('templates/header', $data);
        $this->load->view('pages/blog/index');
        $this->load->view('templates/footer');
       
    }
   
    public function index_display() {
       
        // $this->output->enable_profiler(TRUE);
       
        // Set default variables
        $msg = '';
       
        if($this->input->post('page')){
           
            $pag_container = '';
            $where = '';
           
            // Sanitize the received page  
            $page = $this->input->post('page');
            $cur_page = $page; 
            $page -= 1;
            // Set the number of results to display
            $per_page = 5;
            $previous_btn = true;
            $next_btn = true;
            $first_btn = true;
            $last_btn = true;
            $start = $page * $per_page;
           
            if(!empty($this->input->post('search'))){
                $where = ' AND (post_title LIKE "%%' . $this->input->post('search') . '%%" OR post_content LIKE "%%' . $this->input->post('search') . '%%") ';
            }
           
            // Set the table where we will be querying data
            $table_name = "ci_posts";
           
            // Query the necessary posts
            $all_blog_posts = $this->db->query("
                SELECT * FROM "
. $table_name . "
                WHERE post_type = 'post' AND post_status = 'publish'"
.$where."
                ORDER BY post_date DESC
                LIMIT ?, ?"
, array($start, $per_page) );
           
            // At the same time, count the number of queried posts
            $blogs_count = $this->db->query("
                SELECT COUNT(ID) as blog_count FROM "
. $table_name . "
                WHERE post_type = 'post' AND post_status = 'publish'"
);
           
            // Loop into all the posts
            foreach($all_blog_posts->result() as $key => $post):
               
                // Set the desired output into a variable
                $msg .= '
                <div class = "col-md-12">      
                    <h2><a href="'
. base_url('blog/' . $post->post_name) . '">' . $post->post_title . '</a></h2>
                    <p>'
. $post->post_excerpt . '</p>
                </div>'
;
               
            endforeach;
           
            // Optional, wrap the output into a container
            $msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";
                   
            // This is where the magic happens
            $count = $blogs_count->row();
            $no_of_paginations = ceil($count->blog_count / $per_page);

            if ($cur_page >= 7) {
                $start_loop = $cur_page - 3;
                if ($no_of_paginations > $cur_page + 3)
                    $end_loop = $cur_page + 3;
                else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
                    $start_loop = $no_of_paginations - 6;
                    $end_loop = $no_of_paginations;
                } else {
                    $end_loop = $no_of_paginations;
                }
            } else {
                $start_loop = 1;
                if ($no_of_paginations > 7)
                    $end_loop = 7;
                else
                    $end_loop = $no_of_paginations;
            }
           
            // Pagination Buttons logic        
            $pag_container .= "
            <div class='cvf-universal-pagination'>
                <ul>"
;

            if ($first_btn && $cur_page > 1) {
                $pag_container .= "<li p='1' class='active'>First</li>";
            } else if ($first_btn) {
                $pag_container .= "<li p='1' class='inactive'>First</li>";
            }

            if ($previous_btn && $cur_page > 1) {
                $pre = $cur_page - 1;
                $pag_container .= "<li p='$pre' class='active'>Previous</li>";
            } else if ($previous_btn) {
                $pag_container .= "<li class='inactive'>Previous</li>";
            }
            for ($i = $start_loop; $i <= $end_loop; $i++) {

                if ($cur_page == $i)
                    $pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
                else
                    $pag_container .= "<li p='$i' class='active'>{$i}</li>";
            }
           
            if ($next_btn && $cur_page < $no_of_paginations) {
                $nex = $cur_page + 1;
                $pag_container .= "<li p='$nex' class='active'>Next</li>";
            } else if ($next_btn) {
                $pag_container .= "<li class='inactive'>Next</li>";
            }

            if ($last_btn && $cur_page < $no_of_paginations) {
                $pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
            } else if ($last_btn) {
                $pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
            }

            $pag_container = $pag_container . "
                </ul>
            </div>"
;
           
            // We echo the final output
            echo
            '<div class = "cvf-pagination-content">' . $msg . '</div>' .
            '<div class = "cvf-pagination-nav">' . $pag_container . '</div>';
           
        }  
   
    }

    public function view($post_name) {
   
       
        $data['blog'] = $this->post_model->get_post(array('post_name' => $post_name));

        if (!empty($data['blog'])) {
           
            $data['post_title'] = $data['blog']->post_title;
           
            $this->load->view('templates/header', $data);
            $this->load->view('pages/blog/view', $data);
            $this->load->view('templates/footer');
           
        } else {
            show_404();
        }
   
       
    }
}

Step 3

In your application/view, create another file and name it “view.php”, open view.php and add the following code:

1
2
<h1><?php echo $blog->post_title; ?></h1>
<p><?php echo autop($blog->post_content); ?></p>

The above code will display the contents of the clicked post.

Styling

If you need a quick styling for your pagination, you can add the following code into your css file:

1
2
3
4
5
6
.cvf_pag_loading {padding: 20px;}
.cvf-universal-pagination ul {margin: 0; padding: 0;}
.cvf-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
.cvf-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
.cvf-universal-pagination ul li.inactive {background: #7E7E7E;}
.cvf-universal-pagination ul li.selected {background: #1E8CBE; color: white;}

Now taste the AJAXified pagiantion in action. We have done a great job already.
If you have enjoyed this tutorial please do share with others. You know, sharing means caring :).

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.