Vamos a utilizar dos tablas de bases de datos para hacer la aplicación. En la primera almacenaremos la url y el número de votos que lleva, mientras que en la segunda se almacenarán las ip que han votado a cada página, para que no puedan volver a votar.
De esta forma, la primera tabla la llamaremos “appreciate_pages” tendrá los siguientes campos:
- Id (auto_increment)
- hash (varchar 32, unique)
- url (text)
- aprreciated (int 10)
Mientras que la segunda tabla tendrá como nombre “appreciate_votes” con los siguientes campos:
- Id (auto_increment)
- ip (int 10)
- pageid (int 10)
- dt (timestamp)
Lo primero que haremos será crear el código XHTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>An AJAX Click To Appreciate Badge</title> <link rel="stylesheet" type="text/css" href="styles.css" /> <link rel="stylesheet" type="text/css" href="appreciateMe/appreciate.css"/> </head> <body> <div id="countDiv"></div> <div id="main"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="appreciateMe/plugin.js" type="text/javascript"></script> <script src="script.js" type="text/javascript"></script> </body> </html>
Lo único destacable de aquí, es que la llamada al archivo jQuery lo hacemos desde Google, en vez de tener cargado el archivo en nuestro desarrollo.
Lo siguiente que hacemos es crearnos el archivo PHP para realizar la conexión a la base de datos que hemos creado.
$db_host = 'localhost';
$db_user = 'YourUsername';
$db_pass = 'YouPassword';
$db_name = 'NameOfDB';
@$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno()) {
die('<h1>Could not connect to the database</h1>');
}
$mysqli->set_charset("utf8");
Del código de arriba destaca la creación de un objeto MySQLi en vez de utilizar las clásicas funciones de mysql que nos proporciona php.
A continuación mostramos el código de la página php que hará todo el tema de las consultas a la base de datos, tanto actualizar las votaciones, como registrar la ip en la tabla correspondiente...
/* Setting the error reporting level */
error_reporting(E_ALL ^ E_NOTICE);
include 'connect.php';
if(!$_GET['url'] || !filter_input(INPUT_GET,'url',FILTER_VALIDATE_URL)){
exit;
}
$pageID = 0;
$appreciated = 0;
$jsonArray = array();
$hash = md5($_GET['url']);
$ip = sprintf('%u',ip2long($_SERVER['REMOTE_ADDR']));
// $result is an object:
$result = $mysqli->query("SELECT id,appreciated FROM appreciate_pages WHERE hash='".$hash."'");
if($result)
{
list($pageID,$appreciated) = $result->fetch_row();
// fetch_row() is a method of result
}
// The submit parameter denotes that we need to write to the database
if($_GET['submit'])
{
if(!$pageID)
{
// If the page has not been appreciated yet, insert a new
// record to the database.
$mysqli->query("
INSERT INTO appreciate_pages
SET
hash='".$hash."',
url='".$mysqli->real_escape_string($_GET['url'])."'"
);
if($mysqli->affected_rows){
// The insert_id property contains the value of
// the primary key. In our case this is also the pageID.
$pageID = $mysqli->insert_id;
}
}
// Write the vote to the DB, so the user can vote only once
$mysqli->query("
INSERT INTO appreciate_votes
SET
ip = ".$ip.",
pageid = ".$pageID
);
if($mysqli->affected_rows){
$mysqli->query("
UPDATE appreciate_pages
SET appreciated=appreciated+1 WHERE id=".$pageID
);
// Increment the appreciated field
}
$jsonArray = array('status'=>1);
}
else
{
// Only print the stats
$voted = 0;
// Has the user voted?
$res = $mysqli->query("
SELECT 1 FROM appreciate_votes
WHERE ip=".$ip." AND pageid=".$pageID
);
if($res->num_rows){
$voted = 1;
}
$jsonArray = array('status'=>1,'voted'=>$voted,'appreciated'=>$appreciated);
}
// Telling the browser to interpret the response as JSON:
header('Content-type: application/json');
echo json_encode($jsonArray);
El código está divido en dos partes. Una de ellas que obtiene el valor a mostrar de las votaciones que lleva ya asignadas la url y otra parte donde se realizan las actualizaciones y los registros en la base de datos.
Como la solicitud la vamos a realizar por medio de AJAX, al final pasamos los datos obtenidos como objeto JSON, lo que nos facilitará después el tratamiento y ahorraremos ancho de banda.
A continuación mostramos el archivo plugin.js, encargado de realizar el control de las acciones de la aplicación cuando se realice la pulsación del botón.
function(){
$.appreciateButton = function(options){
// The options object must contain a URL and a Holder property
// These are the URL of the Appreciate php script, and the
// div in which the badge is inserted
if(!'url' in options || !'holder' in options){
return false;
}
var element = $(options.holder);
// Forming the url of the current page:
var currentURL = window.location.protocol+'//'+
window.location.host+window.location.pathname;
// Issuing a GET request. A rand parameter is passed
// to prevent the request from being cached in IE
$.get(options.url,{url:currentURL,rand:Math.random()},function(response){
// Creating the appreciate button:
var button = $('<a>',{
href:'',className:'appreciateBadge',
html:'Appreciate Me'
});
if(!response.voted){
// If the user has not voted previously,
// make the button active / clickable.
button.addClass('active');
}
else button.addClass('inactive');
button.click(function(){
if(button.hasClass('active')){
button.removeClass('active').addClass('inactive');
if(options.count){
// Incremented the total count
$(options.count).html(1 + parseInt(response.appreciated));
}
// Sending a GET request with a submit parameter.
// This will save the appreciation to the MySQL DB.
$.getJSON(options.url,{url:currentURL,submit:1});
}
return false;
});
element.append(button);
if(options.count){
$(options.count).html(response.appreciated);
}
},'json');
return element;
}
})(jQuery);
En el archivo script.js, se hará la llamada a la función que hemos creado anteriormente, pasándoles los parámetros a utilizar.
$(document).ready(function(){
// Creating an appreciate button.
$.appreciateButton({
url : 'appreciateMe/script.php', // URL to the PHP script.
holder : '#main', // The button will be inserted here.
count : '#countDiv' // Optional. Will show the total count.
});
});
Por último solo nos queda darle algo de estilo a la aplicación. Veamos estos estilos, que hemos dividido en dos archivos.
El primero es appreciate.css, y el código es el siguiente.
.appreciateBadge{
width:129px;
height:129px;
display:block;
text-indent:-9999px;
overflow:hidden;
background:url('sprite.png') no-repeat;
text-decoration:none;
border:none;
}
.appreciateBadge.active{
background-position:left top;
}
.appreciateBadge.active:hover{
background-position:0 -129px;
}
.appreciateBadge.inactive{
background-position:left bottom;
cursor:default;
}
El segundo archivo es styles.css
#main{
margin:80px auto;
width:130px;
}
#countDiv{
color:#eee;
font-size:35px;
margin-right:120px;
position:absolute;
right:50%;
top:265px;
}
Podéis ver una demo aquí.
Vía: tutorialzine.com






