Foros del Web » Programando para Internet » PHP »

Star rating system - PHP + javascript

Estas en el tema de Star rating system - PHP + javascript en el foro de PHP en Foros del Web. Saludos, estoy creando un sistema de valoraciones para los usuarios, ahora mismo tengo el codigo javascript funcionando correctamente para cada uno de los productos de ...
  #1 (permalink)  
Antiguo 13/04/2015, 12:00
 
Fecha de Ingreso: marzo-2015
Mensajes: 2
Antigüedad: 9 años, 1 mes
Puntos: 0
Star rating system - PHP + javascript

Saludos, estoy creando un sistema de valoraciones para los usuarios, ahora mismo tengo el codigo javascript funcionando correctamente para cada uno de los productos de la base de datos, por lo que estoy intentando que ahora el usuario pueda subir dicha valoración a la base de datos y esta sea recuperada.
Para tal proposito tengo este codigo javascript:
$(function(){
$('body').on({
mousemove: function(e){
var $this = $(this);
// Calculate number of stars
var currentMousePosition = e.pageX - $this.offset().left;
var width = $this.width();
var rounded = Math.round((currentMousePosition/width)*10);

var starNumber = rounded/2;

// Remove + add Classes + Store current rating
$this.removeClass().addClass('stars s-' + starNumber).attr('data-rating', starNumber);
},
mouseleave:function(){
var $this = $(this);
$this.removeClass().addClass('stars s-' + $this.attr('data-default'));
},
click: function(){
var $this = $(this);
//Hide the current rating selector
$this.replaceWith($('<div>', {
'class': 'loading'
}));

// Send the request
$.post('rating.php',{
rating: $this.attr('data-rating')
}, function(d){
// Handle response
if(d.result == 'error'){
alert(d.msg);
} else {
$this.removeClass().addClass('stars s-' + d.rating).attr('data-default', d.rating)
$('.loading').replaceWith($this);
}
}, 'json');
}
}, '.stars');
});

Con este PHP:

<?php

// Error function that stops script processing with die
function error($message){
$output = json_encode(
array(
'result' => 'error',
'msg' => $message
)
);
die($output);
}

// Round to the nearest 0.5
function roundToNearestHalf($number){
return round($number * 2) / 2;
}

// Instantiate database connection
$db = new mysqli('localhost', 'root', '', 'appbiblio');

// Check that the connection worked
if($db->connect_errno > 0){
error('Unable to connect to database [' . $db->connect_error . ']');
}

// Verify that we have enough post items
if(count($_POST) > 1){
error('Too many post items received.');
}

// Check that the rating was entered
if(!isset($_POST['rating']) || $_POST['rating'] == ''){
error('No rating value provided.');
}

// Valid the rating amount that was entered.
if(!preg_match("/[0-5](?:\.5)/", $_POST['rating']) && $_POST['rating'] < 0 && $_POST['rating'] > 5){
error('Invalid rating provided.');
}

// Check if the user has rated before
$sql = <<<SQL
SELECT `ratingid`
FROM `ratings`
WHERE `ip` = '{$_SERVER['REMOTE_ADDR']}'
SQL;

if(!$result = $db->query($sql)){
error('There was an error running the query [' . $db->error . ']');
}

// Tell the user that they have voted already.
if($result->num_rows){
error('That IP address has already voted, please try using another IP.');
}

// Store the user's rating.
$rating = $db->escape_string($_POST['rating']);

$sql = <<<SQL
INSERT INTO `ratings`
(`rating`, `ip`)
VALUES ('{$rating}', '{$_SERVER['REMOTE_ADDR']}')
SQL;

if(!$db->query($sql)){
error('Unable to insert rating to database [' . $db->error . ']');
}

// Get the average rating
$sql = <<<SQL
SELECT AVG(`rating`) AS `rating`
FROM `ratings`
SQL;

if(!$result = $db->query($sql)){
error('There was an error running the query [' . $db->error . ']');
}

// Fetch the average rating
$data = $result->fetch_assoc();

$rating = $data['rating'];

// Output the average rating for the front end to handle
$output = json_encode(
array(
'result' => 'success',
'rating' => roundToNearestHalf($rating)
)
);
echo $output;
?>

El caso es que se queda cargando sin subir nada a la base de datos diciendo que el elemento no existe, aunque detecta el archivo PHP.

Como puedo solucionarlo?

Muchas gracias.

Etiquetas: javascript, mysql, rating, select, sql, system, usuarios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:29.