Javascript
:
Code:
<script type="text/javascript">
var http
function rate(video_id, rating) {
http = open_http()
var url="{$base->path}/?module=videos&action=rate&video_id=" + video_id + "&rating=" + rating
http.onreadystatechange = update_rating(video_id)
http.open("GET", url, TRUE)
http.send(NULL)
}
function update_rating(video_id) {
if(http.readyState == 4 || http.readyState == "complete") {
document.getElementById(video_id).innerHTML = http.responseText
}
}
function open_http() {
var http = NULL
if(window.XMLHttpRequest) {
http = new XMLHttpRequest()
}
else if(window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
}
return http
}
</script>
PHP:
PHP Code:
<?php
/* Jon Mooring
jon@elementsixstudio.com */
#define action variable
if($isset($_GET['action'])) {
$action = $_GET['action'];
}
#different action options
switch($action) {
#video rating block
case('rate'):
#only rate if valid
if(isset($_GET['video_id']) AND isset($_GET['rating']) AND !isset($_COOKIE['rating['.$_GET['video_id'].']'])) {
$rating_data = $db->query_fetch_array("SELECT * FROM {$db->prefix}ratings
WHERE `video_id` = '{$_GET['video_id']}';");
$count = ($rating_data['count'] + 1);
#recalculate average
switch($_GET['rating']) {
case(0):
$average = round(($rating_data['average'] / $count), 2);
break;
case(1):
$average = round((($rating_data['average'] + 1) / $count), 2);
break;
}
#set "already rated" cookie
setcookie('rating['.$_GET['video_id'].']', '1', (time() * 3600 * 24 * 365));
#update rating in database
$db->query("UPDATE {$db->prefix}ratings
SET `count` = '{$count}', `average` = '{$average}'
WHERE `video_id` = '{$_GET['video_id']}';");
#return new rating
echo('<strong>'.$average.'</strong> / 1.00 (<strong>'.$count.'</strong> votes)');
}
break;
}
?>
HTML:
HTML Code:
<strong>{$videos_data['title']}</strong>
<br /><br />
<strong>Description:</strong> {$videos_data['description']}
<strong>Rating:</strong> <span id="{$videos_data['video_id']}"><strong>{$videos_data['average']}</strong> / 1.00 (<strong>{$videos_data['count']}</strong> votes)</span> <a href="" onclick="rate({$videos_data['video_id']}, 1)">+</a> <a href="" onclick="rate({$videos_data['video_id']}, 0)">-</a>
<br />
The rating refuses to even update in the database. Any ideas? I assume it is because I have a flaw in my AJAX code, because I've tested the PHP code manually through my browser and it works fine.