-1

I am using a jquery star rating plugin.the link is (http://irfandurmus.com/projects/jquery-star-rating-plugin/). I want to click the star and it will give me a value ,so I can pass it to database with php. I've broken the plugin many times trying to get it working, but to no avail. It display well in website but I can not store the value in database.Maybe I should modify the js file but I don't know how.Here it is:

;(function($){
    $.fn.rating = function(callback){
        
        callback = callback || function(){};

        // each for all item
        this.each(function(i, v){
            
            $(v).data('rating', {callback:callback})
                .bind('init.rating', $.fn.rating.init)
                .bind('set.rating', $.fn.rating.set)
                .bind('hover.rating', $.fn.rating.hover)
                .trigger('init.rating');
        });
    };
    
    $.extend($.fn.rating, {
        init: function(e){
            var el = $(this),
                list = '',
                isChecked = null,
                childs = el.children(),
                i = 0,
                l = childs.length;
            
            for (; i < l; i++) {
                list = list + '<a class="star" title="' + $(childs[i]).val() + '" />';
                if ($(childs[i]).is(':checked')) {
                    isChecked = $(childs[i]).val();
                };
            };
            
            childs.hide();
            
            el
                .append('<div class="stars">' + list + '</div>')
                .trigger('set.rating', isChecked);
            
            $('a', el).bind('click', $.fn.rating.click);            
            el.trigger('hover.rating');
        },
        set: function(e, val) {
            var el = $(this),
                item = $('a', el),
                input = undefined;
            
            if (val) {
                item.removeClass('fullStar');
                
                input = item.filter(function(i){
                    if ($(this).attr('title') == val)
                        return $(this);
                    else
                        return false;
                });
                
                input
                    .addClass('fullStar')
                    .prevAll()
                    .addClass('fullStar');
            }
            
            return;
        },
        hover: function(e){
            var el = $(this),
                stars = $('a', el);
            
            stars.bind('mouseenter', function(e){
                // add tmp class when mouse enter
                $(this)
                    .addClass('tmp_fs')
                    .prevAll()
                    .addClass('tmp_fs');
                
                $(this).nextAll()
                    .addClass('tmp_es');
            });
            
            stars.bind('mouseleave', function(e){
                // remove all tmp class when mouse leave
                $(this)
                    .removeClass('tmp_fs')
                    .prevAll()
                    .removeClass('tmp_fs');
                
                $(this).nextAll()
                    .removeClass('tmp_es');
            });
        },
        click: function(e){
            e.preventDefault();
            var el = $(e.target),
                container = el.parent().parent(),
                inputs = container.children('input'),
                rate = el.attr('title');
                
            matchInput = inputs.filter(function(i){
                if ($(this).val() == rate)
                    return true;
                else
                    return false;
            });
            
            matchInput
                .prop('checked', true)
                .siblings('input').prop('checked', false);
            
            container
                .trigger('set.rating', matchInput.val())
                .data('rating').callback(rate, e);
        }
    });
    
})(jQuery);

The mysql database exists as follows

CREATE TABLE IF NOT EXISTS `rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `vote` float NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1

I want use this php code to get the star rate value but have no way.

<?php

function connect() {
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "rating";
  $con = mysqli_connect($hostname, $username, $password, $dbname);  
  return $con;
}

function getRatingByProductId($con, $productId) {
    $query = "SELECT SUM(vote) as vote, COUNT(vote) as count from rating WHERE product_id = $productId";

      $result = mysqli_query($con, $query);
      $resultSet = mysqli_fetch_assoc($result);
      if($resultSet['count']>0) {
        return ($resultSet['vote']/$resultSet['count']);
      } else {
        return 0;
      }
    
}
if(isset($_REQUEST['type'])) {
    if($_REQUEST['type'] == 'save') {
        $vote = $_REQUEST['vote'];
        $productId = $_REQUEST['productId'];
          $query = "INSERT INTO rating (product_id, vote) VALUES ('$productId', '$vote')";
          // get connection
          $con = connect();
          $result = mysqli_query($con, $query);
          echo 1; exit;
    } 
}

?>
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 26 '21 at 15:13

1 Answers1

0

You can use bellow jQuery code to submit star on database.

jQuery('.stars .star').click(function(){
    var starValue = $(this).closest('.stars').find('.fullStar').length;
    console.log(starValue);

    // Send starValue value with ajax and store on database
});
Naresh Goyani
  • 39
  • 2
  • 8
  • but how to send starValue value .I write this-----> $.ajax({ url: "trygo.php", type: "POST", data:{"myData":starValue}, And my trygo.php is showed here mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbname) or die(mysql_error()); // Retrieve data from Query String $myData = $_GET['myData']; Is it right?I get erro and the myData variable can not define – bruceherring May 27 '21 at 04:08
  • On console there are print selected star value when you click on any star ? – Naresh Goyani May 27 '21 at 04:43
  • yes ,you are right.I see the value from the console1,2,3,4,5 – bruceherring May 27 '21 at 05:00
  • but I can not pass the starValue .$.ajax({ url: "trygo.php", type: "POST", data:{"myData":starValue}, url : "trygo.php", type : "POST", //dataType : 'json', data : { 'starValue':starValue, }, try and failed – bruceherring May 27 '21 at 05:09
  • You are accessing wrong parameter. On you ajax code you are sending starValue key and on php you use $_GET['myData']. can you try to use $_GET['starValue'] – Naresh Goyani May 27 '21 at 11:45
  • I have " POST "In ajax ,can you tell me why should I use ”$_GET" in php,are they all right? I try all of them ,but I get blank when I open the brower – bruceherring May 28 '21 at 02:53
  • Can you try with $_REQUEST, Its common for both GET & POST. – Naresh Goyani May 28 '21 at 04:17
  • the right value is the myData .it is not starValue.I try it.If you want to send variable with ajax ,you can not use post ,you should use "get". I read from some comment in starkoverflow. But how to get the $_REQUEST in PHP file,it still does not work. I think it is normal,because you set a variable ,when the variable will change,so ,it can not get it in PHP file . – bruceherring May 28 '21 at 05:24