jQueryを使ってブックマークのような星を作ろうとしています。残念ながら、私が持っているのは片道だけです。つまり、リンクに星が付いていない場合は正常に星を付けますが、リンクが既に星が付いていて星を外したい場合、星の画像はページから完全に消えますが、バックエンドでは機能しますが、フロントエンドでは星画像が完全に消えます。
HTMLに次のものがあります。
require_once('connection.inc.php');
$con = dbConnect('read');
$sql = "SELECT * FROM trn_bookmark";
$result = $con->query($sql) or die(mysqli_error());
while($row = $result->fetch_assoc()) {
$className = "star";
if($row['bookmark_flag'] == 'Y'){
$className = "favorited";
}
echo '<div id="'.$row['bookmark_id'].'"><a href="javascript:void(0);" class="'.$className.'"></a> <span>'.$row['bookmark_desc'].'</span></div>';
}
CSS:
.star {
background-color: transparent;
background-image: url('star-off.png');
background-repeat:no-repeat;
display: block;
height:16px;
width:16px;
float:left;
}
.favorited {
text-indent: -5000px;
background-color: transparent;
background-image: url('star-on.png');
background-repeat:no-repeat;
height:16px;
width:16px;
float:left;
}
JavaScript 関数は次のとおりです。
$(document).ready(function(){
$('.star,.favorited').click(function() {
var id = $(this).parents('div').attr('id');
var className = $(this).attr('class');
var flag = (className=='star') ? 'Y':'N';
var $this = $(this);
$.ajax({
type: "post",
url: "conversation.php",
cache: false,
data:{'bookmarkId': id,'flag':flag},
success: function(response){
if(response=='true'){
$this.toggleClass("favorited");
}
},
error: function(){
alert('Error while request..');
}
});
});
});
そして、conversation.php:
$bookmarkId = $_POST['bookmarkId'];
$flag = $_POST['flag'];
require_once('connection.inc.php');
$con = dbConnect('read');
$stmt = $con->stmt_init();
$sql = "UPDATE trn_bookmark SET bookmark_flag = ? WHERE bookmark_id = '$bookmarkId'";
if ($stmt->prepare($sql)) {
$stmt->bind_param('s', $flag);
$done = $stmt->execute();
}
echo 'true';
ライブの様子が見れるようにアップしました。このリンクで何が起こっているかを確認できます: http://www.rytenet.com/starrating/index.php