+ Reply to Thread
Results 1 to 6 of 6

Thread: Jquery + PHP rating - zmena v realnom case

  1. #1

    Jquery + PHP rating - zmena v realnom case

    na adrese
    Code:
    http://www.g-explorer.com/skuska-ratingu.php
    testujem rating a neviem si dat rady s tymto:
    Chcem aby sa pri ohodnoteni (je pouzity fade efekt) v realnom case updatovali aj tie nizsie hodnoty - link vyssie (teda aj tie 2 textove a hviezdicky)
    Toto updatovanie sa udeje ale az po refreshi prehliadaca a ja to chcem v realnom case

    Cely rating script je z dvoch suborov

    1. rating.php
    Code:
    <?php
    class rating{
    
    	public $average = 0;
    	public $votes;
    	public $status;
    	public $table;
    	private $path;
    	
    	function __construct($table){
    		try{
    			$pathinfo = pathinfo(__FILE__);
    			$this->path = realpath($pathinfo['dirname']) . "/database/ratings.sqlite";
    			$dbh = new PDO("sqlite:$this->path");
    			$this->table = $dbh->quote($table);
    			// check if table needs to be created
    			$table_check = $dbh->query("SELECT * FROM $this->table WHERE id='1'");
    			if(!$table_check){
    				// create database table
    				$dbh->query("CREATE TABLE $this->table (id INTEGER PRIMARY KEY, rating CEIL(3,2), ip VARCHAR(15))");
    				$dbh->query("INSERT INTO $this->table (rating, ip) VALUES (0, 'master')");				
    			} else {
    				$this->average = $table_check->fetchColumn(1);
    			}
    			$this->votes = ($dbh->query("SELECT COUNT(*) FROM $this->table")->fetchColumn()-1);
    		}catch( PDOException $exception ){
    				die($exception->getMessage());
    		}
    		$dbh = NULL;		
    	}
    
    	function set_score($score, $ip){
    		try{
    			$dbh = new PDO("sqlite:$this->path");
    			$voted = $dbh->query("SELECT id FROM $this->table WHERE ip='$ip'");
    			if(sizeof($voted->fetchAll())==0){
    				
    				$dbh->query("INSERT INTO $this->table (rating, ip) VALUES ($score, '$ip')");
    				$this->votes++;
    				
    				//cache average in the master row
    				$statement = $dbh->query("SELECT rating FROM $this->table");
    				$total = $quantity = 0;
    				$row = $statement->fetch(); //skip the master row
    				while($row = $statement->fetch()){
    					$total = $total + $row[0];
    					$quantity++;
    				}
    															$this->average = round((($total*10)/$quantity),0);
    				$statement = $dbh->query("UPDATE $this->table SET rating = $this->average WHERE id=1");
    				$this->status = 'Děkujeme za vaše hodnocení!';
    			} else {
    				$this->status = 'Už jste hlasovali';
    			}
    			
    		}catch( PDOException $exception ){
    				die($exception->getMessage());
    		}
    		$dbh = NULL;
    	}
    };
    
    function rating_form($table){
    	$ip = $_SERVER["REMOTE_ADDR"];
    	if(!isset($table) && isset($_GET['table'])){
    		$table = $_GET['table'];
    	}
    	$rating = new rating($table);
    	$status = "<div class='score'>
    				<a class='score-1' href='?score=1&amp;table=$table&amp;user=$ip'>1</a>
    				<a class='score-2' title='!'  href='?score=2&amp;table=$table&amp;user=$ip'>2</a>
    				<a class='score-3' title='30% (Špatná)' href='?score=3&amp;table=$table&amp;user=$ip'>3</a>
    				<a class='score-4' title='40% (Špatná)' href='?score=4&amp;table=$table&amp;user=$ip'>4</a>
    				<a class='score-5' title='50% (Průměrná)' href='?score=5&amp;table=$table&amp;user=$ip'>5</a>
    					<a class='score-6' title='60% (Průměrná)' href='?score=6&amp;table=$table&amp;user=$ip'>6</a>
    				<a class='score-7' title='70% (Velmi dobrá)'  href='?score=7&amp;table=$table&amp;user=$ip'>7</a>
    				<a class='score-8' title='80% (Velmi dobrá)' href='?score=8&amp;table=$table&amp;user=$ip'>8</a>
    				<a class='score-9' title='90% (Perfektní)' href='?score=9&amp;table=$table&amp;user=$ip'>9</a>
    				<a class='score-10' title='100% (Perfektní)' href='?score=10&amp;table=$table&amp;user=$ip'>10</a>
    			</div>
    	";
    	if(isset($_GET['score'])){
    		$score = $_GET['score'];
    		if(is_numeric($score) && $score <=10 && $score >=1 && ($table==$_GET['table']) && isset($_GET["user"]) && $ip==$_GET["user"]){
    			$rating->set_score($score, $ip);
    			$status = $rating->status;
    		}
    	}
    	if(!isset($_GET['update'])){ echo "<div id='user-rating-box'>"; }
    	?>
    
    	<span>Hodnocení uživatelů</span>
    		<span class="user-rating"><span style="width:<?php echo $rating->average; ?>%"><span><?php echo $rating->average; ?>%</span></span></span>
    		<span class="votes"><?php echo $rating->votes; ?> hlasů</span>
    		<div class="status">
    			<?php echo $status; ?>
    		</div>
    
    	<?php
    	if(!isset($_GET['update'])){ echo "</div>"; }
    }
    
    if(isset($_GET['update'])&&isset($_GET['table'])){
    	rating_form($_GET['table']);
    }
    
    
    
    
    
    
    function rating_img($table){
    
    	$rating = new rating($table);
    
    	?>
    
    		<span class="user-rating"><span style="width:<?php echo $rating->average; ?>%"><span><?php echo $rating->average; ?>%</span></span></span>
    	
    	<?php
    		
    }
    
    
    
    function rating_value($table){
    
    	$rating = new rating($table);
    	
    	?>
    
    	<?php echo $rating->average; ?>%
    	
    	<?php
    	
    }
    
    
    
    
    function rating_box($table){
    
    	$rating = new rating($table);
    
    	if($rating->average >=30 && $rating->average <=100){ echo "<div>"; }
    	if($rating->average <30 && $rating->average >0){ echo "<div>"; }
    
    	?>
    
    	<?php echo $rating->average; ?>%
    	
    	<?php
    
    	if($rating->average <30 && $rating->average >0){ echo "</div>"; }
    		if($rating->average >=30 && $rating->average <=100){ echo "</div>"; }
    }




    2. rating.js
    Code:
    $(document).ready(function() {
    	$('.status').prepend("<div class='score_this'><a href='#'>Ohodnotit</a></div>");
    	$('.score_this').click(function(){
    		$(this).slideUp();
    		return false;
    	});
    	
    	$('.score a').click(function() {
    		$(this).parent().parent().parent().addClass('scored');
    		$.get("../../res/rating/rating.php" + $(this).attr("href") +"&update=true", {}, function(data){
    			$('.scored').fadeOut("normal",function() {
    				$(this).html(data);
    				$(this).fadeIn();
    				$(this).removeClass('scored');
    			});
    		});
    		return false; 
    	});
    });

  2. #2
    Zdravim, no zadany link mi vyhadzuje 403 error tak ze neviem co vlastne potrebujes, lebo nevidim finalny produkt. Ked som si presiel kod vyzera celkom pouzitelne cize neviem povedat, kde presne by mohol byt problem. Postujem tu vsak svoj jednoduchy rating ktory splna to co potrebujes, avsak udaje sa ukladaju do TXT suboru, nie do SQL databazy. Dufam ze pomoze.

    ratings.php
    Code:
    <?php
    error_reporting(0);
    $rating = new ratings($_POST['widget_id']);
    isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
        
        
    class ratings {
        
        public $data_file = 'ratings.data.txt';
        private $widget_id;
        private $data = array();
        
        
    public function __construct($wid) 
    {
        $this->widget_id = $wid;
    	$all = file_get_contents($this->data_file);
        
        if($all) 
    	{
            $this->data = unserialize($all);
        }
    }
    
    public function get_ratings() 
    {
        if($this->data[$this->widget_id]) 
    	{
            echo json_encode($this->data[$this->widget_id]);
        }
        else 
    	{
            $data['widget_id'] = $this->widget_id;
            $data['number_votes'] = 0;
            $data['total_points'] = 0;
            $data['dec_avg'] = 0;
            $data['whole_avg'] = 0;
            echo json_encode($data);
        } 
    }
    public function vote() 
    {
        # Get the value of the vote
        preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
        $vote = $match[1];
        
        $ID = $this->widget_id;
        # Update the record if it exists
        if($this->data[$ID]) 
    	{
            $this->data[$ID]['number_votes'] += 1;
            $this->data[$ID]['total_points'] += $vote;
        }
        # Create a new one if it doesn't
        else 
    	{
            $this->data[$ID]['number_votes'] = 1;
            $this->data[$ID]['total_points'] = $vote;
        }
        
        $this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
        $this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
            
            
        file_put_contents($this->data_file, serialize($this->data));
        $this->get_ratings();
    }
    }
    ?>
    rating.js
    Code:
    // This is the first thing we add ------------------------------------------
        $(document).ready(function() {
            
            $('.rate_widget').each(function(i) {
                var widget = this;
                var out_data = {
                    widget_id : $(widget).attr('id'),
                    fetch: 1
                };
                $.post(
                    'class/ratings.php',
                    out_data,
                    function(INFO) {
                        $(widget).data( 'fsr', INFO );
                        set_votes(widget);
                    },
                    'json'
                );
            });
        
    
            $('.ratings_stars').hover(
                // Handles the mouseover
                function() {
                    $(this).prevAll().andSelf().addClass('ratings_over');
                    $(this).nextAll().removeClass('ratings_vote'); 
                },
                // Handles the mouseout
                function() {
                    $(this).prevAll().andSelf().removeClass('ratings_over');
                    // can't use 'this' because it wont contain the updated data
                    set_votes($(this).parent());
                }
            );
            
            
            // This actually records the vote
            $('.ratings_stars').bind('click', function() {
                var star = this;
                var widget = $(this).parent();
                
                var clicked_data = {
                    clicked_on : $(star).attr('class'),
                    widget_id : $(star).parent().attr('id')
                };
                $.post(
                    'class/ratings.php',
                    clicked_data,
                    function(INFO) {
                        widget.data( 'fsr', INFO );
                        set_votes(widget);
                    },
                    'json'
                ); 
            });
            
            
            
        });
    
        function set_votes(widget) {
    
            var avg = $(widget).data('fsr').whole_avg;
            var votes = $(widget).data('fsr').number_votes;
            var exact = $(widget).data('fsr').dec_avg;
        
            window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
            
            $(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
            $(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote'); 
            $(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
        }
        // END FIRST THING
    A ak to chces pouzit staci includovat js a php file a urobit nieco taketo

    Code:
    <div id='r".$row['id_zlavy']."' class='rate_widget'>
            <div class='star_1 ratings_stars'></div>
            <div class='star_2 ratings_stars'></div>
            <div class='star_3 ratings_stars'></div>
            <div class='star_4 ratings_stars'></div>
            <div class='star_5 ratings_stars'></div>
        </div>
    A samozrejme nejake to CSS

    Code:
    .rate_widget 
    {
        width: 100px;
        height: 15px;
        margin: 0;
        padding: 0;
        float: left;
        border: 0;
    }
    
    .ratings_stars 
    {
    background: url('images/star_gray.png') no-repeat;
    float:      left;
    height:     15px;
    padding:    2px;
    padding-top: 3px;
    width:      14px;
    }
    .ratings_vote 
    {
    background: url('images/star.png') no-repeat;
    }
    .ratings_over 
    {
    background: url('images/star.png') no-repeat;
    }
    Neviem ci to pomoze, ale dufam ze ano.
    Všetko o hrách a novinkách s herného sveta nájdete na http://the-guild.cz/.

  3. #3
    Quote Originally Posted by Werewolf View Post
    Zdravim, no zadany link mi vyhadzuje 403 error tak ze neviem co vlastne potrebujes, lebo nevidim finalny produkt. Ked som si presiel kod vyzera celkom pouzitelne cize neviem povedat, kde presne by mohol byt problem. Postujem tu vsak svoj jednoduchy rating ktory splna to co potrebujes, avsak udaje sa ukladaju do TXT suboru, nie do SQL databazy. Dufam ze pomoze.
    uz som tent link opravil
    Code:
    http://www.g-explorer.com/skuska-ratingu.php
    urcite pochopi co chcem

  4. #4
    Malo by to vy zerat nejako takto ze by sa nizsie uvedeny zapis vlozil pod $.get("../../res/rating/rating.php" + $(this).attr("href") +"&update=true", {}, function(data){

    lenze co ma byt v tomto zapise aby to fungovalo?

    Code:
        $('.abc').fadeOut("normal",function() {
             
       }, "json");

  5. #5
    Hmm, PHP mas dobre. Problem je s Jquery. A ked ze sa v JavaScripte vyzname velmy malo, neporadim ti.
    Všetko o hrách a novinkách s herného sveta nájdete na http://the-guild.cz/.

  6. #6
    Quote Originally Posted by Werewolf View Post
    Hmm, PHP mas dobre. Problem je s Jquery. A ked ze sa v JavaScripte vyzname velmy malo, neporadim ti.
    no jquery ma vyzerat takto co som sa dozvedel
    Code:
    $.get("../../res/rating/rating.php",{"update":"procenta"}, function(data){
       $("#procenta").fadeOut("normal");
       $("#procenta").html(data);
       $("#procenta").fadeIn("normal");
    });
    ale nizsie uvedene mam urobit v php len neviem ako:
    podminkou je vytvoreni spravneho php kodu, ktery vytiskne ty procenta po zavolani rating.php?update=procenta
    a taky mit ty procenta v elementu s id="procenta"

+ Reply to Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts