11485 sujets

JavaScript, DOM et API Web HTML5

Bonjour,

J'utilise le script de vote en ajax sur ce site http://www.tipocode.com/jquery/very-precise-jquery-ajax-star-rating-plugin-tutorial/

Et donc je me suis inspirer pour un système de vote pour une webradio pour chaque chanson.

La base de donnée qui fourni par défaut:

CREATE TABLE IF NOT EXISTS `Ratings` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `media` int(6) NOT NULL,
  `rate` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;


J'ai donc voulu ajouter un champ qui enregistrera le nom de la musique, au final la base de données ressemble a celle ci champs ajouter en gras:

CREATE TABLE IF NOT EXISTS `Ratings` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `media` int(6) NOT NULL,
  [b]`title` varchar VARCHAR(255) NOT NULL,[/b]
  `rate` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;


Voici également la fonction en PHP par défaut:

function starBar($numStar, $mediaId, $starWidth) {
    global $bdd;
    $cookie_name = 'tcRatingSystem2'.$mediaId;
    $nbrPixelsInDiv = $numStar * $starWidth; // Calculate the DIV width in pixel
    
    // Rate average and number of rate from the database
    $query = $bdd->getOne('SELECT round(avg(rate), 2) AS average, count(rate) AS nbrRate FROM tc_tuto_rating WHERE media='.$mediaId.'');
    
    //num of pixel to colorize (in yellow)
    $numEnlightedPX = round($nbrPixelsInDiv * $query['average'] / $numStar, 0);
    
    $getJSON = array('numStar' => $numStar, 'mediaId' => $mediaId); // We create a JSON with the number of stars and the media ID
    $getJSON = json_encode($getJSON);
 
    $starBar = '<div id="'.$mediaId.'">';
    $starBar .= '<div class="star_bar" style="width:'.$nbrPixelsInDiv.'px; height:'.$starWidth.'px; background: linear-gradient(to right, #ffc600 0px,#ffc600 '.$numEnlightedPX.'px,#ccc '.$numEnlightedPX.'px,#ccc '.$nbrPixelsInDiv.'px);" rel='.$getJSON.'>';
    for ($i=1; $i<=$numStar; $i++) {
        $starBar .= '<div title="'.$i.'/'.$numStar.'" id="'.$i.'" class="star"';
        if( !isset($_COOKIE[$cookie_name]) ) $starBar .= ' onmouseover="overStar('.$mediaId.', '.$i.', '.$numStar.'); return false;" onmouseout="outStar('.$mediaId.', '.$i.', '.$numStar.'); return false;" onclick="rateMedia('.$mediaId.', '.$i.', '.$numStar.', '.$starWidth.'); return false;"';
        $starBar .= '></div>';
    }
    $starBar .= '</div>';
    $starBar .= '<div class="resultMedia'.$mediaId.'" style="font-size: small; color: grey">'; // We show the rate score and number of rates
    if ($query['nbrRate'] == 0) $starBar .= 'Not rated yet';
    else $starBar .= 'Rating: ' . $query['average'] . '/' . $numStar . ' (' . $query['nbrRate'] . ' votes)';
    $starBar .= '</div>';
    $starBar .= '<div class="box'.$mediaId.'"></div>';
    $starBar .= '</div>';
    return $starBar;
}


Je l'ai donc modifier légèrement pour ajouter le titre variables ajouter en gras:

function starBar($numStar, $mediaId, [b]$title[/b], $starWidth) {
	
    global $connexion;
	
	$cookie_name = 'RadioOxygen'.$mediaId;
    $nbrPixelsInDiv = $numStar * $starWidth; // Calculate the DIV width in pixel
    
	// Rate average and number of rate from the database
	$stmt = $connexion->prepare('SELECT round(avg(rate), 2) AS average, count(rate) AS nbrRate FROM Ratings WHERE media=:media;');
	$stmt->bindValue(':media', $mediaId, PDO: [langue]ARAM_STR);
	$stmt->execute();
	$donnees = $stmt->fetch(PDO::FETCH_ASSOC);
		
    //num of pixel to colorize (in yellow)
    $numEnlightedPX = round($nbrPixelsInDiv * $donnees['average'] / $numStar, 0);
    
    $getJSON = array('numStar' => $numStar, 'mediaId' => $mediaId, [b]'title' => $title[/b]); // We create a JSON with the number of stars and the media ID
    $getJSON = json_encode($getJSON);
 
    $starBar = '<div id="'.$mediaId.'">';
    $starBar .= '<div class="star_bar" style="width:'.$nbrPixelsInDiv.'px; height:'.$starWidth.'px;" rel='.$getJSON.'>';
    for ($i=1; $i<=$numStar; $i++) {
        $starBar .= '<div title="'.$i.'/'.$numStar.'" id="'.$i.'" class="star"';
        if( !isset($_COOKIE[$cookie_name]) ) $starBar .= ' onmouseover="overStar('.$mediaId.', '.$i.', '.$numStar.'); return false;" onmouseout="outStar('.$mediaId.', '.$i.', '.$numStar.'); return false;" onclick="rateMedia('.$mediaId.', '.[b]$title[/b].', '.$i.', '.$numStar.', '.$starWidth.'); return false;"';
        $starBar .= '></div>';
    }
    $starBar .= '</div>';
    $starBar .= '<div class="resultMedia'.$mediaId.'" style="font-size: small; color: grey">'; // We show the rate score and number of rates
    if ($donnees['nbrRate'] == 0) $starBar .= 'Pas encore évalué';
    else $starBar .= '<strong>' . $donnees['average'] . '</strong>/' . $numStar . ' (' . $donnees['nbrRate'] . ' votes)';
    $starBar .= '</div>';
    $starBar .= '<div class="box'.$mediaId.'"></div>';
    $starBar .= '</div>';
    return $starBar;
}


Je fait donc appelle au vote comme ceci :
echo starBar(5, 'idaleatoire', [b]'titechanson'[/b], 25);


J'ai donc ajouter le title dans la fonction ainsi que dans la fonction javascript rateMedia

Dans le fichier JS j'ai juste ajouter title dans la fonction donc la voici champs ajouter en gras

function rateMedia(mediaId, [b]title[/b], rate, numStar, starWidth) {
	jQuery('#' + mediaId + ' .star_bar #' + rate).removeAttr('onclick'); // Remove the onclick attribute: prevent multi-click
	jQuery('.box' + mediaId).html('<img src="/images/loading2.gif" alt="" />'); // Display a processing icon
	var data = {mediaId: mediaId, title: title, rate: rate}; // Create JSON which will be send via Ajax
	jQuery.ajax({ // JQuery Ajax
		type: 'POST',
		url: '/ajax/ratings.php', // URL to the PHP file which will insert new value in the database
		data: data, // We send the data string
		dataType: 'json',
		timeout: 3000,
		success: function(data) {
			jQuery('.box' + mediaId).html('<div style="font-size: small; color: green">Merci d\'avoir vot&eacute; !</div>'); // Return "Thank you for rating"
			// We update the rating score and number of rates
			jQuery('.resultMedia' + mediaId).html('<div style="font-size: small; color: grey">Rating: ' + data.avg + '/' + numStar + ' (' + data.nbrRate + ' votes)</div>');
			// We recalculate the star bar with new selected stars and unselected stars
			var nbrPixelsInDiv = numStar * starWidth;
			var numEnlightedPX = Math.round(nbrPixelsInDiv * data.avg / numStar);
			jQuery('#' + mediaId + ' .star_bar').attr('style', 'width:' + nbrPixelsInDiv + 'px; height:' + starWidth + 'px,#ccc 100%);');
			jQuery.each(jQuery('#' + mediaId + ' .star_bar > div'), function () {
				jQuery(this).removeAttr('onmouseover onclick');
			});
		},
		error: function() {
			jQuery('#box').text('Problem');
		}
	});
}

function overStar(mediaId, myRate, numStar) {
	for ( var i = 1; i <= numStar; i++ ) {
		if (i <= myRate) jQuery('#' + mediaId + ' .star_bar #' + i).attr('class', 'star_hover');
		else jQuery('#' + mediaId + ' .star_bar #' + i).attr('class', 'star');
	}
}
		 
function outStar(mediaId, myRate, numStar) {
	for ( var i = 1; i <= numStar; i++ ) {
		jQuery('#' + mediaId + ' .star_bar #' + i).attr('class', 'star');
	}
}


Et pour finir je fait donc appelle a la page ratings.php variables ajouter en gras

include '../inc/config.php';
 
if($_POST) {
	$mediaId = $_POST['mediaId'];
	[b]$title = $_POST['title'];[/b]
	$rate = $_POST['rate'];
	
	$expire = 24*3600; // 1 day
	setcookie('RadioOxygen'.$mediaId, 'rated', time() + $expire, '/'); // Place a cookie

	$r = 'INSERT INTO Ratings VALUES (:id, :media, [b]:title[/b], :rate)';
	$req = $connexion->prepare($r);
	$req->execute(array(
		'id' => '', 
		'media' => $mediaId,
		[b]'title' => $title,[/b]
		'rate' => $rate
	));
			
	$stmt = $connexion->prepare('SELECT round(avg(rate), 2) AS average, count(rate) AS nbrRate FROM Ratings WHERE media=:media;');
	$stmt->bindValue(':media', $mediaId, PDO: [langue]ARAM_STR);
	$stmt->execute();
	$donnees = $stmt->fetch(PDO::FETCH_ASSOC);
		
	$dataBack = array('avg' => $donnees['average'], 'nbrRate' => $donnees['nbrRate']);
	$dataBack = json_encode($dataBack);
	
	echo $dataBack;
}


Ici aussi j'ai donc ajouter title une fois le vote créer. Voila pour l'explication. Par contre j'ai une seule erreur que Firebug me dit au moment du clic sur les étoiles :

ReferenceError: le titre de la chanson is not defined <!DOCTYPE html>


Merci pour votre aide et vos futurs réponses en espérant m'avoir bien exprimer Smiley cligne

Cordialement
Modifié par subzeros (28 Apr 2015 - 17:48)
Bonsoir,

C'est parcequ'il faut mettre les paramètres que tu fais passer à ta fonction rateMedia entre guillemets si ce sont des chaines de caractère. Essaie comme ça :
onclick="rateMedia('.$mediaId.', "'.$title.'", '.$i.', '.$numStar.', '.$starWidth.'); [...]
//                               ^          ^
//                           avec des guillemets ici et là