We post tutorials, articles or blogs either to our own blog site or as a user to other sites. Sometimes we need to let user rate on our tutorials or articles or blogs so that we know how much that blog is famous or how much that blog is intended to be accepted by readers.

Here I am going to show you how we can implement a simple voting/rating system using AJAX, Codeigniter so that everyone will get an idea how to do it. In this example I have given one sample content on which you can rate this. The rating/voting system is calculated by taking average on accumulated votes on five stars. Once you give vote/rate from your system you cannot give vote or rate next time. As soon as you cast your vote or rate you can see it instantly the updated vote as well as you can also see what vote/rate you have cast. When you mouse over on stars you can see the highlighted stars on how many stars vote/rate you want to cast.

If you have any query please feel free to leave a comment.

Prerequisites

Knowledge of PHP & Codeigniter, jQuery and AJAX
MySQL 5.x
Apache HTTP server 2.2, 2.4
Codeigniter 2.1.4, 3.0.6
Netbeans 7.x, 8.0.2

Project folder structure in Netbeans IDE

Codeigniter AJAX Vote/Rate System

You need to create assets folder in parallel to application folder for putting all asset files such as js, css, images etc.

Final Output

When you run the application

Codeigniter AJAX vote/rate system

When you mouse over stars

Codeigniter AJAX vote/rate system

When you cast your vote/rate
Codeigniter AJAX vote/rate system

Step 1. First thing is we need to create database table

DROP TABLE IF EXISTS `blog_vote`;

CREATE TABLE `blog_vote` (
  `vote_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `blog_vote` float unsigned NOT NULL,
  `blog_id` int(10) unsigned NOT NULL,
  `ip_address` varchar(20) COLLATE latin1_general_ci DEFAULT NULL,
  PRIMARY KEY (`vote_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Step 2. Once you have codeigniter framework setup in place then configure database settings at location application/config/database.php

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'cdcol';

Step 3. Create a assets helper file under /application/helpers/assets_helper.php which gives us the URL for different assets like css, js etc.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

function assets_url() {
    return base_url();
}

/* End of file assets_helper.php */
/* Location: ./application/helpers/assets_helper.php */

Step 4. Modify the autoload.php file at location application/config/autoload.php as follows

$autoload['libraries'] = array('database');

$autoload['helper'] = array('url', 'file', 'assets', 'text', 'form');

Step 5. Create a model which will give us the data for the vote/rate under application/models/blogmodel.php. The below model file is pretty simple.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of blogmodel
 *
 * @author https://roytuts.com
 */
class BlogModel extends CI_Model {

    private $blog_vote = 'blog_vote';

    function __construct() {
        
    }

    function get_blog_rating($blog_id) {
        $sql = 'SELECT COUNT(DISTINCT(bv.vote_id)) total_rows,
            IFNULL(SUM(bv.blog_vote),0) total_rating, bv.blog_id
            FROM ' . $this->blog_vote . ' bv
            WHERE bv.blog_id=' . $blog_id . ' LIMIT 1';
        $query = $this->db->query($sql);
        $row = $query->row();
        $total_rows = $row->total_rows;
        $total_rating = $row->total_rating;
        $results['vote_rows'] = $total_rows;
        $rating = 0;
        if ($total_rows > 0) {
            $rating = $total_rating / $total_rows;
        }
        $dec_rating = round($rating, 1);
        $results['vote_rate'] = $rating;
        $results['vote_dec_rate'] = $dec_rating;
        return $results;
    }

    function get_blog_rating_from_ip($blog_id) {
        $ip = $this->input->server('REMOTE_ADDR');
        $sql = 'SELECT bv.vote_id
            FROM ' . $this->blog_vote . ' bv
            WHERE bv.ip_address=' . $this->db->escape($ip) .
                ' AND bv.blog_id=' . $blog_id;
        $this->db->limit(1);
        $query = $this->db->query($sql);
        if ($query->num_rows() > 0) {
            $row = $query->row();
            $vote_id = $row->vote_id;
            $sql = 'SELECT IFNULL(SUM(bv.blog_vote),0) total_rating,
                bv.blog_id
                FROM ' . $this->blog_vote . ' bv  
                WHERE bv.blog_id=' . $blog_id .
                    ' LIMIT 1';
            $query = $this->db->query($sql);
            $row = $query->row();
            $rating = $row->total_rating;
            $rating = round($rating, 1);
            $results['vote_rate'] = $rating;
            return $results;
        }
    }

    /*
     * rate this blog
     */

    function rate_blog($blog_id, $rating) {
        $ip = $this->input->server('REMOTE_ADDR');
        $sql = 'SELECT bv.vote_id
            FROM ' . $this->blog_vote . ' bv
            WHERE bv.ip_address=' . $this->db->escape($ip) .
                ' AND bv.blog_id=' . $blog_id;
        $this->db->limit(1);
        $query = $this->db->query($sql);
        if ($query->num_rows() > 0) {
            $row = $query->row();
            $vote_id = $row->vote_id;
            $sql = 'SELECT IFNULL(SUM(bv.blog_vote),0) total_rating,
                bv.blog_id
                FROM ' . $this->blog_vote . ' bv
                WHERE bv.vote_id=' . $vote_id . '
                AND bv.blog_id=' . $blog_id .
                    ' LIMIT 1';
            $query = $this->db->query($sql);
            $row = $query->row();
            $rating = $row->total_rating;
            $rating = round($rating, 1);
            $results['vote_curr_rate'] = $rating;
        } else {
            $this->db->trans_start(TRUE);
            $data = array(
                'blog_vote' => $rating,
                'blog_id' => $blog_id,
                'ip_address' => $ip
            );
            $this->db->insert($this->blog_vote, $data);
            $this->db->trans_complete();
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
            } else {
                $this->db->trans_commit();
                $sql = 'SELECT IFNULL(SUM(bv.blog_vote),0) total_rating,
                bv.blog_id
                FROM ' . $this->blog_vote . ' bv
                WHERE bv.blog_id=' . $blog_id .
                        ' LIMIT 1';
                $query = $this->db->query($sql);
                $row = $query->row();
                $rating = $row->total_rating;
                $rating = round($rating, 1);
                $results['vote_curr_rate'] = $rating;
            }
        }
        $overall_results = $this->get_blog_rating($blog_id);
        $results['vote_rows'] = $overall_results['vote_rows'];
        $results['vote_rate'] = $overall_results['vote_rate'];
        $results['vote_dec_rate'] = $overall_results['vote_dec_rate'];
        return $results;
    }

}

/* End of file blogmodel.php */
/* Location: ./application/models/blogmodel.php */

Step 6. Now create one controller called BlogController under application/controller/blogcontroller.php with below code

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of blogcontroller
 *
 * @author https://roytuts.com
 */
class BlogController extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('blogmodel', 'blog');
    }

    function index() {
        //the hard-coded blog id value 1 should come from UI
        $blog_id = 1;
        $vote_results = $this->blog->get_blog_rating($blog_id);
        $data['blog_vote_overall_rows'] = $vote_results['vote_rows'];
        $data['blog_vote_overall_rate'] = $vote_results['vote_rate'];
        $data['blog_vote_overall_dec_rate'] = $vote_results['vote_dec_rate'];
        $vote_results = $this->blog->get_blog_rating_from_ip($blog_id);
        $data['blog_vote_ip_rate'] = $vote_results['vote_rate'];
        $this->load->view('blog', $data);
    }

    function rate_blog() {
        if (isset($_POST)) {
            $blog_id = $_POST['blog_id'];
            $rating = $_POST['rating'];
            $vote_results = $this->blog->rate_blog($blog_id, $rating);
            $blog_vote_overall_rows = $vote_results['vote_rows'];
            $blog_vote_overall_rate = $vote_results['vote_rate'];
            $blog_vote_overall_dec_rate = $vote_results['vote_dec_rate'];
            $blog_vote_ip_rate = $vote_results['vote_curr_rate'];
            $stars = '';
            for ($i = 1; $i <= floor($blog_vote_overall_rate); $i++) {
                $stars .= '<div class="star" id="' . $i . '"></div>';
            }
            //THE OVERALL RATING (THE OPAQUE STARS)
            echo '<div class="r"><div class="rating">' . $stars . '</div>' .
            '<div class="transparent">
                <div class="star" id="1"></div>
                <div class="star" id="2"></div>
                <div class="star" id="3"></div>
                <div class="star" id="4"></div>
                <div class="star" id="5"></div>
                <div class="votes">(' . $blog_vote_overall_dec_rate . '/5, ' . $blog_vote_overall_rows . ' ' . ($blog_vote_overall_rows > 1 ? ' votes' : ' vote') . ') ' . ($blog_vote_ip_rate > 0 ? '<strong>You rated this: <span style="color:#39C;">' . $blog_vote_ip_rate . '</span></strong>' : '') . '</div>
              </div>
            </div>';
        }
    }

}

Step 7. Now modify the application/config/routes.php file as follows

$route['default_controller'] = "blogcontroller";

Step 8. Next create a view with the following code under /application/views/blog.php

<?php
$overall_vote_rows = $blog_vote_overall_rows;
$overall_vote_rate = $blog_vote_overall_rate;
$overall_vote_dec_rate = $blog_vote_overall_dec_rate;
$ip_vote_rate = $blog_vote_ip_rate;
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title>Voting System</title>
        <!--[if IE]> <script> (function() { var html5 = ("abbr,article,aside,audio,canvas,datalist,details," + "figure,footer,header,hgroup,mark,menu,meter,nav,output," + "progress,section,time,video").split(','); for (var i = 0; i < html5.length; i++) { document.createElement(html5[i]); } try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} })(); </script> <![endif]-->
        <link type="text/css" rel="stylesheet" href="<?php echo base_url(); ?>assets/css/blog_rating.css"/>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/jquery-1.9.1.min.js"></script>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/blog_rating.js"></script>
    </head>
    <body>
        <div class='singlepost'>
            <div class='fullpost clearfix'>
                <div class='entry'>
                    <h1 class='post-title'>
                        This is a sample blog content
                    </h1>
                    <p>
                        Posted By:&nbsp;roytuts.com,&nbsp;&nbsp;
                        Posted On:&nbsp;25-08-2015
                    </p>
                    <input type="hidden" name="blog_content_id" id="blog_content_id" value="1"/>
                    <?php
                    $stars = '';
                    echo '<div id="ajax_vote">';
                    for ($i = 1; $i <= floor($overall_vote_rate); $i++) {
                        $stars .= '<div class="star" id="' . $i . '"></div>';
                    }
                    //THE OVERALL RATING (THE OPAQUE STARS)
                    echo '<div class="r"><div class="rating">' . $stars . '</div>';

                    //THE TRANSPARENT STARS (OPAQUE STARS WILL COVER AS MANY STARS AS THE RATING REPRESENTS)
                    echo '<div class="transparent">
                <div class="star" id="1"></div>
                <div class="star" id="2"></div>
                <div class="star" id="3"></div>
                <div class="star" id="4"></div>
                <div class="star" id="5"></div>
                <div class="votes">(' . $blog_vote_overall_dec_rate . '/5, ' . $overall_vote_rows . ' ' . ($overall_vote_rows > 1 ? ' votes' : ' vote') . ') ' . ($blog_vote_ip_rate > 0 ? '<strong>You rated this: <span style="color:#39C;">' . $blog_vote_ip_rate . '</span></strong>' : '') . '</div>
              </div>
            </div>';
                    echo '</div>';
                    ?>
                    <div>&nbsp;</div>
                    <p style="text-align: justify;">
                        The topic of blogging seems to come up a lot in our social media training workshops. The benefits of a quality blog are obvious – fresh content is good for your readers and your rankings. Blogs are easy to set up and even easier to update. We often tell people that if they can use Microsoft Word… they can update a blog.

                        As easy as they are to set up, they can be difficult to maintain. A good blog is filled with relevant, timely content that is updated on a regular basis. New bloggers often start out with a bang but then fizzle out when they realize that creating content can be challenging.
                    </p>
                </div>
            </div>
        </div>
    </body>
</html>

Step 9. Download the assets directory and put it under project root directory

assets

Step 10. Run the application.

Download source code here ci

That’s all. Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

18 thoughts on “Codeigniter, AJAX Voting/Rating System

  1. Thanks sir for your tutorial, i really want to share this article and rewrite it in my language. I ask your permision for me rewrite it in my own language sir. Thanks for this tutor, you are the best

  2. Hello i m running the project on localhost and when i rate it pop up a window javascript and gives me a message
    [object]/[object] and it doesn’t update the value..plz contact with me with e-mail to sent you a screenshot

      1. i have download the assets and i copy everything in my codeigniter and i build my sql as yours but i get that error i use the latest version of codeigniter 3

          1. I have tested the same code with Codeigniter 3, it is working fine. You must be doing something wrong. Please check your source code.

  3. Can you please give me your project?When I go to rate It’s always show me a screan [object] [object] and I can’t rate.I can’t solve the problem.So please can you give me this project?

Leave a Reply

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