How To Like Dislike Jquery Ajax PHP

How To Like Dislike Jquery Ajax PHP

How To Like Dislike Jquery Ajax PHP

0 Sales

Free

To know what the audience thinks about your proposal, the rating system is very beneficial. The concept as well as the consumer will value various products or services. Rating lets the consumer think about how good or bad a product or service is. It also helps the owner understand the product drawbacks and know if the product meets the expectations of the customer or not.

 

The rating system is very useful if you want to get customer feedback. Web admin can monitor the like and dislike of the user through the rating system. It will also help webmaster understand the choices made by the user and make their website more engaging with the guests.In order to obtain customer or audience review, most e-commerce websites or blogs implement the rating system.

 

The functionality of the rating system can be implemented easily using jQuery and PHP. In this tutorial, we'll show you how to use jQuery, Ajax, PHP, and MySQL to build a simple rating system. With jQuery and Ajax, the example rating system takes the like or dislike of the visitor. In addition, ranking data is stored using PHP and MySQL in the server. When determined the maximum number of likes and dislikes, it will be shown to the guests. We're going to simplify the entire process and you can quickly integrate the rating system in your design.

 

PHP's OOP definition will be used to make the entire script simpler, faster and easier to extend. In the like hate rating system using PHP, the following features will be introduced.

 

  • Use the like and dislike button to collect the posts information from the server and list.

  • The like or dislike number of the particular post will be changed by pressing the like or dislike button.

  • The number like and dislike will be displayed next to the button.

Create Database Table

A table must be built in the database to store the post information, and two fields needed to hold the same number and hate it. The following SQL creates a table of posts in the MySQL database with some basic fields.

 

CREATE TABLE `posts` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `content` text COLLATE utf8_unicode_ci NOT NULL,

 `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `like_num` bigint(10) NOT NULL,

 `dislike_num` bigint(10) NOT NULL,

 `created` datetime NOT NULL,

 `modified` datetime NOT NULL,

 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Post Class (Post.class.php)

The Post class performs all the server operations. For example, connect, insert, update, and delete post data in the database to the MySQL database server. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword) and name ($dbName) according to the credentials of your database server.

 

  • constructor() –The MySQL server is connected.

  • GetRows() –Records from the posts table and returns the posts as an array based on the conditions specified.

  • Insert() –Place the post information in the table of comments.

  • Update() –Update posting information in the table of comments.

 

<?php

/*

 * Post Class

 * This class is used for database related (connect, insert, and update) operations

 * @author    CodexWorld.com

 * @url        http://www.codexworld.com

 * @license    http://www.codexworld.com/license

 */

class Post{

    private $dbHost     = "localhost";

    private $dbUsername = "root";

    private $dbPassword = "root";

    private $dbName     = "codexworld";

    private $tblName    = "posts";

    

    public function __construct(){

        if(!isset($this->db)){

            // Connect to the database

            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);

            if($conn->connect_error){

                die("Failed to connect with MySQL: " . $conn->connect_error);

            }else{

                $this->db = $conn;

            }

        }

    }

    

    /*

     * Returns rows from the database based on the conditions

     * @param string name of the table

     * @param array select, where, order_by, limit and return_type conditions

     */

    public function getRows($conditions = array()){

        $sql = 'SELECT ';

        $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';

        $sql .= ' FROM '.$this->tblName;

        if(array_key_exists("where",$conditions)){

            $sql .= ' WHERE ';

            $i = 0;

            foreach($conditions['where'] as $key => $value){

                $pre = ($i > 0)?' AND ':'';

                $sql .= $pre.$key." = '".$value."'";

                $i++;

            }

        }

        

        if(array_key_exists("order_by",$conditions)){

            $sql .= ' ORDER BY '.$conditions['order_by']; 

        }

        

        if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){

            $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 

        }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){

            $sql .= ' LIMIT '.$conditions['limit']; 

        }

        

        $result = $this->db->query($sql);

        

        if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){

            switch($conditions['return_type']){

                case 'count':

                    $data = $result->num_rows;

                    break;

                case 'single':

                    $data = $result->fetch_assoc();

                    break;

                default:

                    $data = '';

            }

        }else{

            if($result->num_rows > 0){

                while($row = $result->fetch_assoc()){

                    $data[] = $row;

                }

            }

        }

        return !empty($data)?$data:false;

    }

    

    /*

     * Insert data into the database

     * @param string name of the table

     * @param array the data for inserting into the table

     */

    public function insert($data){

        if(!empty($data) && is_array($data)){

            $columns = '';

            $values  = '';

            $i = 0;

            if(!array_key_exists('created',$data)){

                $data['created'] = date("Y-m-d H:i:s");

            }

            if(!array_key_exists('modified',$data)){

                $data['modified'] = date("Y-m-d H:i:s");

            }

            foreach($data as $key=>$val){

                $pre = ($i > 0)?', ':'';

                $columns .= $pre.$key;

                $values  .= $pre."'".$val."'";

                $i++;

            }

            $query = "INSERT INTO ".$this->tblName." (".$columns.") VALUES (".$values.")";

            $insert = $this->db->query($query);

            return $insert?$this->db->insert_id:false;

        }else{

            return false;

        }

    }

    

    /*

     * Update data into the database

     * @param string name of the table

     * @param array the data for updating into the table

     * @param array where condition on updating data

     */

    public function update($data,$conditions){

        if(!empty($data) && is_array($data)){

            $colvalSet = '';

            $whereSql = '';

            $i = 0;

            if(!array_key_exists('modified',$data)){

                $data['modified'] = date("Y-m-d H:i:s");

            }

            foreach($data as $key=>$val){

                $pre = ($i > 0)?', ':'';

                $colvalSet .= $pre.$key."='".$val."'";

                $i++;

            }

            if(!empty($conditions)&& is_array($conditions)){

                $whereSql .= ' WHERE ';

                $i = 0;

                foreach($conditions as $key => $value){

                    $pre = ($i > 0)?' AND ':'';

                    $whereSql .= $pre.$key." = '".$value."'";

                    $i++;

                }

            }

            $query = "UPDATE ".$this->tblName." SET ".$colvalSet.$whereSql;

            $update = $this->db->query($query);

            return $update?$this->db->affected_rows:false;

        }else{

            return false;

        }

    }

}

?>

Posts with Like Dislike Rating (index.php)

All posts will be retrieved from the server in the index.php folder and will be listed for rating with the like and dislike key.

 

JavaScript Code:

 

This instance uses jQuery and Ajax to save page-free refresh score in the server, including the jQuery library.

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 

CwRating() is a custom JavaScript function that sends the post ID and rating type via AJAX to the rating.php file. Show the rating number on the counter like or hate based on the Ajax response.

 

<script>

/**

 * cwRating() function sends a request to the server-side

 * to insert like or dislike number in the database.

 * On success, shows the rating number count to the specified element.  

 *

 * Author: CodexWorld

 * 

 * @param id - Unique ID to save like or dislike for this respective ID.

 * @param type - Use 1 for like and 0 for dislike.

 * @param target - The div ID where the total number of likes or dislikes will display.

 * 

 */

function cwRating(id,type,target){

    $.ajax({

        type:'POST',

        url:'rating.php',

        data:'id='+id+'&type='+type,

        success:function(msg){

            if(msg == 'err'){

                alert('Some problem occured, please try again.');

            }else{

                $('#'+target).html(msg);

            }

        }

    });

}

</script>

 

PHP & HTML Code

Initially, the posts information will be retrieved from the server using Post category and described with some basic details and buttons like & dislike. Clicking the rating buttons will activate the cwRating() function and pass these parameters to the counter–post ID, rating type(1=Like, 0=Dislike), HTML component.

 

<?php

// Load and initialize post class

require_once 'Post.class.php';

$post = new Post();


// Get posts data

$posts = $post->getRows();

?>


<div class="row">

    <?php if(!empty($posts)){ foreach($posts as $row){ ?>

    <div class="col-sm-4 col-lg-4 col-md-4">

        <div class="thumbnail">

            <img src="<?php echo 'images/'.$row['image']; ?>" />

            <div class="caption">

                <h4><?php echo $row['title']; ?></h4>

                <p><?php echo $row['content']; ?></p>

            </div>

            <div class="ratings">

                <p class="pull-right"></p>

                <p>

                    <!-- Like button -->

                    <span class="glyphicon glyphicon-thumbs-up" onClick="cwRating(<?php echo $row['id']; ?>, 1, 'like_count<?php echo $row['id']; ?>')"></span>&nbsp;

                    <!-- Like counter -->

                    <span class="counter" id="like_count<?php echo $row['id']; ?>"><?php echo $row['like_num']; ?></span>&nbsp;&nbsp;&nbsp;

                    

                    <!-- Dislike button -->

                    <span class="glyphicon glyphicon-thumbs-down" onClick="cwRating(<?php echo $row['id']; ?>, 0, 'dislike_count<?php echo $row['id']; ?>')"></span>&nbsp;

                    <!-- Dislike counter -->

                    <span class="counter" id="dislike_count<?php echo $row['id']; ?>"><?php echo $row['dislike_num']; ?></span>

                </p>

            </div>

        </div>

    </div>

    <?php } } ?>

</div>

 

Like/Dislike Rating Number Counter (rating.php)


 

The.php rating file manages the features to save the server rating number.

 

  • Using $POST in PHP to retrieve the post ID from the Ajax email.

  • Use the Post Class method getRows() to get information from the server based on the post ID.

  • Update like or dislike rating number ($POST['type']) using Post class update() form.

  • Return the number similar or dislike to the Ajax request success feature.


 

<?php

// Load and initialize post class

require_once 'Post.class.php';

$post = new Post();


if(!empty($_POST['id'])){

    

    // Get post data

    $conditions['where'] = array(

        'id' => $_POST['id']

    );

    $conditions['return_type'] = 'single';

    $postData = $post->getRows($conditions);

    

    // Post total likes

    $postLike = $postData['like_num'];

    

    // Post total dislikes

    $postDislike = $postData['dislike_num'];

    

    // Calculates the numbers of like or dislike

    if($_POST['type'] == 1){

        $like_num = ($postLike + 1);

        $upData = array(

            'like_num' => $like_num

        );

        $return_count = $like_num;

    }else{

        $dislike_num = ($postDislike + 1);

        $upData = array(

            'dislike_num' => $dislike_num

        );

        $return_count = $dislike_num;

    }

    

    // Update post like or dislike

    $condition = array('id' => $_POST['id']);

    $update = $post->update($upData, $condition);

    

    // Return like or dislike number if update is successful, otherwise return error

    echo $update?$return_count:'err';

}

?>

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 15, 2020

Updated Date : Jun 17, 2021

Ratings

Comments : 0

Downloads : 0