<form method="post" action="/vote.php">
<input type="hidden" name="item" value="999">
<input type="submit" name="submit" value="Vote Up">
</form>
<?php
if( !isset( $_POST['item'] ) ) {
header( 'HTTP/1.0 404 Not Found' );
die( '<html><body>Missing <i>item</i> parameter</body></html>' );
}
$item = (int) $_POST['item'];
if( @mysql_query( "UPDATE `items` SET `vote`=`vote`+1 WHERE `id`=$item" ) ) {
if( isset( $_POST['format'] ) && $_POST['format']=='json' )
die( json_encode( array( 'result'=>true ) ) );
die( '<html><body>Score for item #'.$item.' incremented</body></html>' );
}
header( 'HTTP/1.1 500 Internal Server Error' );
if( isset( $_POST['format'] ) && $_POST['format']=='json' )
die( json_encode( array( 'result'=>false ) ) );
die( '<html><body>Score for item #'.$item.' FAILED to incremented</body></html>' );
jQuery
$( document ).ready( function() {
$( 'form[action="/vote.php"]' ).each( function() {
$( this ).replaceWith( '<span class="vote" parameter="item='+$( this ).find( 'input[name="item"]' ).attr( 'value' )+'">Vote Up</span>' );
} );
$( 'span[class="vote"]' ).click( function() {
var $this = $( this );
$.ajax( {
type : 'POST' ,
url : '/vote.php' ,
data : $( this ).attr( 'parameter' )+'&format=json' ,
dataType : 'json' ,
success : function( data , status , XHR ) {
if( data.result===true )
alert( 'Voted Up' );
else
alert( 'Something Unexpected Borked' );
} ,
error : function( XHR , status , error ) {
alert( 'Something Borked' );
}
} );
} );
} );
ACTUALIZADO: Comportamiento modificado a POST basado en el consejo de @Artefacto.