JavaScriptとPHPを使用していいねボタンを実装しました。
いいねボタンを押すとカウント数がプラスされ、ボタンの色が変わります。
もう一度押すと、カウント数がマイナスされ、ボタンの色が元に戻ります。
ボタン機能自体の実装は上手くいったのですが、次にページを訪れた際に前回と同じ(いいねボタンを押していたらボタンの色が変わった)状態を維持してページを表示することができずにいます。
jquery.cookie.jsを使用してcookie処理で実装できないか試していました。
以下ソースになります。
index.php
<?php // カウント数取得関数 function get_count($file) { $filename = 'data/'.$file.'.dat'; $fp = @fopen($filename, 'r'); if ($fp) { $vote = fgets($fp, 9182); } else { $vote = 0; } return $vote; } ?> <!DOCTYPE HTML> <html lang="ja"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="jquery.cookie.js"></script> <script> var likeBtn = { init: function() { this.vote(); this.clickEvent(); this.setParam(); }, setParam: function() { this.ajaxFlag =true; }, clickEvent: function() { var myself = this; $('.btn_vote').on('click', function() { if (myself.ajaxFlag) { myself.ajaxFlag = false; $(this).toggleClass('on'); var getParent = $(this).parents('section'); var image = getParent.children('.img'); image.toggleClass('is-view'); var id = $(this).attr('id'); $(this).hasClass('on') ? myself.vote(id, 'plus') : myself.vote(id, 'minus'); } }); if($.cookie('siteview')) { // クッキーがある場合の処理 $.removeCookie("siteview" , { path: "/" }); } else { // クッキーがない場合の処理 $.cookie('siteview', '1', {expires: 7}); } }, vote: function(id, plus) { var myself = this; cls = $('.' + id); cls_num = Number(cls.html()); count = plus == 'minus' ? cls_num - 1 : cls_num + 1; $.post('vote.php', { 'file': id, 'count': count }, function(data) { if (data == 'success') cls.html(count); setTimeout(function() { myself.ajaxFlag = true; }, 1000); }); } }; $(function() { likeBtn.init(); }); </script> <body> <section> <p class="img"><img src="img/pic_01.jpg" width="100%" alt="ねこ"></p> <div class="btn_area"> <h2>ねこ</h2> <p class="ico_heart vote_01"><?= get_count('vote_01') ?></p> <p class="btn_vote" id="vote_01"></p> </div><!-- /btn_area --> </section> </body> </html>
vote.php
<?php // カウントアップ処理 $file = $_POST['file']; $count = $_POST['count']; $check = $_SERVER['HTTP_X_REQUESTED_WITH']; if ($file && $count && $check && strtolower($check) == 'xmlhttprequest') { $filename = 'data/'.$file.'.dat'; $fp = @fopen($filename, 'w'); flock($fp, LOCK_EX); fputs($fp, $count); flock($fp, LOCK_UN); fclose($fp); echo 'success'; } ?>
ボタンをクリック → ajaxでデータをvote.phpに送信 → カウントアップ処理を行い.datファイルに書き込み → .datファイル内の内容を取得し表示という流れです。
index.php内の// クッキーがある場合の処理、// クッキーがない場合の処理、この2つの部分にどのような記述をすれば良いのか、またcookie処理を別の場所に記述するべきなのかなどアドバイスいただければ幸いです。
よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/12 04:38