Forums / Cotonti / Core Labs / multiple page ratings.

Elgan
#1 2009-04-04 10:57
hey so im not a fan of javascript or a guru and hardly know it. but i gave this a go, it all works, posting it here as i dont actually know what to do with it and plan to sleep more tomorrow. some can look, validate, improve, check js etc. To fix the issue of multiple ratings on a single page.

ive implamented the code on my demo site here.
http://www.mods-r-us.net/demo/plug.php?e=medialibrary&category=2

Plus some people could look through and slate.

i noticed on the star plugin they released a new version. so i downlaoded this to implament as new usually means better.
was this wrong? as the last jquery.rating.js had been edited for cotonti. I thought if i didnt edit it, it would be easier to update later tho.
so i havent.

jquery.rating.js is default and downloaded here
http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.rating.js

because of the update i also used the css from their new version download here
http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.rating.css



ratings.tpl
<!-- BEGIN: RATINGS -->


<!-- BEGIN: RATINGS_INCLUDES -->
	<script type="text/javascript" src="js/jquery.rating.js"></script>
	<script type="text/javascript">
	//<![CDATA[
	$(function() {
		$('.rating_submit').hide();

		/*
			### Default implementation ###
		*/
		$('input[type=radio].star').rating
		(
			//options
			{
				half: true,
				callback: function(value, link) 
				{
					ratingval = link.getAttribute('tabindex');
					$('[name=' + $(this).attr("name") + '].rating_submit').show();
				}
			}
		); 


		$('.rating_submit').click(
			function() {
				
				var name =  $(this).attr("name");
				var formname = 'newrating_' + name;
				var datastr = $("#" + formname).serialize();
				//datastr += '&rcde=' + name;
				
				//hide away the submit button again
				$('[name=' + name + '].rating_submit').hide();
				
				//get rating block
				var rating = $('[name=' + name + '].rating');				
				//get rating_average block
				var rating_average = $('[name=' + name + '].rating_average');				

				rating.hide();

				ajaxSend({
					method: 'POST',
					formId: formname,
					divId: 'loading',
					data:  datastr,
				});
				
				var getdata = "&rcde=" + name;
				var get_url = "{RATINGS_AJAX_REQUEST}";
				get_url += "&rcde=" + name;
				//append which rating we are to the get url
				$.get(get_url,
					{
					'rcde=': name
					},

					function(data) 
					{
						if(data)
						{	
							
							rating_average.addClass('rating').removeClass('rating_average').show();
							rating_average.replaceWith('<div name="' + name + '" class="rating">'+data+'</div>');
							rating.remove();
						}
						else
						{
							//alert("failed");
							rating.show();
						}
					}					
				);

				return false;
		});
	});
	//]]>
	</script>
	<!-- END: RATINGS_INCLUDES -->
<!-- BEGIN: NOTVOTED -->

<form action="{RATINGS_FORM_SEND}" method="post" id="{FORM_NAME}" name="{FORM_NAME}" style="display:inline;clear:none;margin:0;padding:0">
	<div class="rating" name="{RATING_NAME}">
		<!-- BEGIN: RATINGS_ROW -->
			<noscript>{RATINGS_ROW_VALUE}</noscript>
			<input type="radio" name="{RATING_NAME}" type="radio" class="star" value="{RATINGS_ROW_VALUE}" title="{RATINGS_ROW_TITLE}" {RATINGS_ROW_CHECKED} {RATINGS_ROW_DISABLED}/>
		<!-- END: RATINGS_ROW -->

		<input type="submit" value="{PHP.skinlang.ratings.Rateit}" class="rating_submit"  name="{RATING_NAME}" />
	</div>

	<div style="display:inline;clear:none;margin:0;padding:0">
		<div name="{RATING_NAME}" class="rating_average" style="display:none;">
			{RATINGS_FANCYIMG}
		</div>
	</div>

</form>

<!-- END: NOTVOTED -->

<!-- BEGIN: VOTED -->
<div style="display:inline;clear:none;margin:0;padding:0">
	<div name="{RATING_NAME}" class="rating">
		{RATINGS_FANCYIMG}
	</div>
</div>
<!-- END: VOTED -->

<!-- END: RATINGS -->


sed_build_ratings

function sed_build_ratings($code, $url, $display)
{
	global $db_ratings, $db_rated, $db_users, $cfg, $usr, $sys, $L;
	static $called = false;

	//$url .= '&amp;rcde='.$code;
	$is_code = sed_import('rcde','G','ALP');
	$p_is_code = sed_import('rcde','P','ALP');

	$is_code = (!empty($p_is_code)) ? $p_is_code : $is_code;

	//if we are not the comment element thats being updated then skip
	if(!empty($is_code) )
	{
		if($is_code != $code)
		{
			return (array('',''));
		}
		else{


		}
	}

	list($usr['auth_read_rat'], $usr['auth_write_rat'], $usr['isadmin_rat']) = sed_auth('ratings', 'a');

	if ($cfg['disable_ratings'] || !$usr['auth_read_rat'])
	{
		return (array('',''));
	}

	$sql = sed_sql_query("SELECT * FROM $db_ratings WHERE rating_code='$code' LIMIT 1");

	if($row = sed_sql_fetcharray($sql))
	{
		$rating_average = $row['rating_average'];
		$yetrated = TRUE;
		if($rating_average<1)
		{ $rating_average = 1; }
		elseif ($rating_average>10)
		{ $rating_average = 10; }
		$rating_cntround = round($rating_average, 0);
	}
	else
	{
		$yetrated = FALSE;
		$rating_average = 0;
		$rating_cntround = 0;
	}
	$rating_fancy =  '';
	for($i = 1; $i <= 10; $i++)
	{
		$checked = $i == $rating_cntround ? 'checked="checked"' : '';
		$star_class = ($i <= $rating_cntround) ? 'star-rating star_group_newrate star-rating-readonly star-rating-on' : 'star-rating star_group_newrate star-rating-readonly';
		$star_margin = (in_array(($i/2), array(1,2,3,4,5))) ? '-8' : '0';
		$rating_fancy .= '<div style="width: 8px;" class="'.$star_class.'"><a style="margin-left: '.$star_margin.'px;" tabindex="'.$i.'" title="'.$L['rat_choice' . $i].'">&nbsp;</a></div>';
	}
	if(!$display)
	{
		return array($rating_fancy, '');
	}

	if($_GET['ajax'])
	{
		ob_clean();
		echo $rating_fancy;
		ob_flush();
		exit;
	}

	$sep = mb_strstr($url, '?') ? '&amp;' : '?';

	$t = new XTemplate(sed_skinfile('ratings'));

	$t->assign(array(
	'RATING_NAME' => $code,
	"FORM_NAME" => "newrating_$code",
	));

	$inr = sed_import('inr','G','ALP');

	//$newrate = sed_import('newrate','P','INT');
	$newrate = sed_import($code,'P','INT');
	$newrate = (!empty($newrate)) ? $newrate : 0;

	if(!$cfg['ratings_allowchange'])
	{
		$alr_rated = sed_sql_result(sed_sql_query("SELECT COUNT(*) FROM ".$db_rated." WHERE rated_userid=".$usr['id']." AND rated_code = '".sed_sql_prep($code)."'"), 0, 'COUNT(*)');
	}
	else
	{
		$alr_rated = 0;
	}


	if ($inr=='send' && $newrate>=0 && $newrate<=10 && $usr['auth_write_rat'] && $alr_rated<=0)
	{
		/* == Hook for the plugins == */
		$extp = sed_getextplugins('ratings.send.first');
		if (is_array($extp))
		{ foreach($extp as $k => $pl) { include_once($cfg['plugins_dir'].'/'.$pl['pl_code'].'/'.$pl['pl_file'].'.php'); } }
		/* ===== */

		$sql = sed_sql_query("DELETE FROM $db_rated WHERE rated_code='".sed_sql_prep($code)."' AND rated_userid='".$usr['id']."' ");

		if (!$yetrated)
		{
			$sql = sed_sql_query("INSERT INTO $db_ratings (rating_code, rating_state, rating_average, rating_creationdate, rating_text) VALUES ('".sed_sql_prep($code)."', 0, ".(int)$newrate.", ".(int)$sys['now_offset'].", '') ");
		}

		$sql = ($newrate) ? sed_sql_query("INSERT INTO $db_rated (rated_code, rated_userid, rated_value) VALUES ('".sed_sql_prep($code)."', ".(int)$usr['id'].", ".(int)$newrate.")") : '';
		$sql = sed_sql_query("SELECT COUNT(*) FROM $db_rated WHERE rated_code='$code'");
		$rating_voters = sed_sql_result($sql, 0, "COUNT(*)");
		if ($rating_voters>0)
		{
			$ratingnewaverage = sed_sql_result(sed_sql_query("SELECT AVG(rated_value) FROM $db_rated WHERE rated_code='$code'"), 0, "AVG(rated_value)");
			$sql = sed_sql_query("UPDATE $db_ratings SET rating_average='$ratingnewaverage' WHERE rating_code='$code'");
		}
		else
			{ $sql = sed_sql_query("DELETE FROM $db_ratings WHERE rating_code='$code' "); }

		/* == Hook for the plugins == */
		$extp = sed_getextplugins('ratings.send.done');
		if (is_array($extp))
		{ foreach($extp as $k => $pl) { include_once($cfg['plugins_dir'].'/'.$pl['pl_code'].'/'.$pl['pl_file'].'.php'); } }
		/* ===== */



		header('Location: ' . SED_ABSOLUTE_URL . $url);
		exit;

	}

	if ($usr['id']>0)
	{
		$sql1 = sed_sql_query("SELECT rated_value FROM $db_rated WHERE rated_code='$code' AND rated_userid='".$usr['id']."' LIMIT 1");

		if ($row1 = sed_sql_fetcharray($sql1))
		{
			$alreadyvoted = ($cfg['ratings_allowchange']) ? FALSE : TRUE;
			$rating_uservote = $L['rat_alreadyvoted']." (".$row1['rated_value'].")";
		}
	}
	if(!$called && $usr['id']>0 && !$alreadyvoted)
	{
		// Link JS and CSS
		$sep = mb_strstr($url, '?') ? '&' : '?';
		$t->assign('RATINGS_AJAX_REQUEST', $url . $sep .'ajax=true');
		$t->parse('RATINGS.RATINGS_INCLUDES');
		$called = true;
	}
	/* == Hook for the plugins == */
	$extp = sed_getextplugins('ratings.main');
	if (is_array($extp))
	{ foreach($extp as $k => $pl) { include_once($cfg['plugins_dir'].'/'.$pl['pl_code'].'/'.$pl['pl_file'].'.php'); } }
	/* ===== */

	$sep = mb_strstr($url, '?') ? '&amp;' : '?';

	if ($yetrated)
	{
		$sql = sed_sql_query("SELECT COUNT(*) FROM $db_rated WHERE rated_code='$code' ");
		$rating_voters = sed_sql_result($sql, 0, "COUNT(*)");
		$rating_average = $row['rating_average'];
		$rating_since = $L['rat_since']." ".date($cfg['dateformat'], $row['rating_creationdate'] + $usr['timezone'] * 3600);
		if ($rating_average<1)
		{ $rating_average = 1; }
		elseif ($ratingaverage>10)
		{ $rating_average = 10; }

		$rating = round($rating_average,0);
		$rating_averageimg = "<img src=\"skins/".$usr['skin']."/img/system/vote".$rating.".gif\" alt=\"\" />";
		$sql = sed_sql_query("SELECT COUNT(*) FROM $db_rated WHERE rated_code='$code' ");
		$rating_voters = sed_sql_result($sql, 0, "COUNT(*)");
	}
	else
	{
		$rating_voters = 0;
		$rating_since = '';
		$rating_average = 0;
		$rating_averageimg = '';
	}

	$t->assign(array(
	"RATINGS_AVERAGE" => $rating_average,
	"RATINGS_RATING" => $rating,
	"RATINGS_AVERAGEIMG" => $rating_averageimg,
	"RATINGS_VOTERS" => $rating_voters,
	"RATINGS_SINCE" => $rating_since,
	"RATINGS_FANCYIMG" => $rating_fancy,
	"RATINGS_USERVOTE" => $rating_uservote
	));

	/* == Hook for the plugins == */
	$extp = sed_getextplugins('ratings.tags');
	if (is_array($extp))
	{ foreach($extp as $k => $pl) { include_once($cfg['plugins_dir'].'/'.$pl['pl_code'].'/'.$pl['pl_file'].'.php'); } }
	/* ===== */

	$vote_block = ($usr['id']>0 && !$alreadyvoted) ? 'NOTVOTED.' : 'VOTED.';
	for($i = 1; $i <= 10; $i++)
	{
		$checked = $i == $rating_cntround ? 'checked="checked"' : '';
		$t->assign(array(
			'RATINGS_ROW_VALUE' => $i,
			'RATINGS_ROW_TITLE' => $L['rat_choice' . $i],
			'RATINGS_ROW_CHECKED' => $checked,
		));
		$t->parse('RATINGS.'.$vote_block.'RATINGS_ROW');
	}
	if($vote_block == 'NOTVOTED.')
	{
		$t->assign("RATINGS_FORM_SEND", $url . $sep . "inr=send&amp;rcde=".$code);
		$t->parse('RATINGS.NOTVOTED');
	}
	else
	{
		$t->parse('RATINGS.VOTED');
	}
	$t->parse('RATINGS');
	$res = $t->text('RATINGS');

	return array($res, '');
}
Trustmaster
#2 2009-04-04 12:04
Will check this later. Could you please use Pastebin for code snippets?
May the Source be with you!