2017-03-26 52 views
-3

我創建了一個類似按鈕,當點擊它,首先檢查用戶是否登錄in.Only登錄,用戶可以點擊按鈕一樣和類似的計數加1.但每次刷新頁面,計數再次變爲0.爲什麼會發生這種情況? HTML:我創建了一個類似按鈕,但刷新頁面後,類似計數變成0

<div class="post-footer"> 
<div class="flag"> 
<span class="flag-wrapper"> 
<a class="flag-action" href="#"> 
<i class="fa fa-heart-o" ></i> 
<span class="count">0</span> 
<span class="flag-text" >Like this news post</span> 
</a> 
</span> 
</div> 
</div> 

的jQuery:

$(document).ready(function(){ 
$(document).on("click", ".flag" ,function(){ 
    // 
    var count = $(".count").text(); 
    // 
    var id= $(".ds-subtitle").attr("rel"); 
    // alert(id); 
    alert(count); 
    $.ajax({ 
     url:"functions/php/like.php", 
     type:"POST", 
     // cache:false, 
     data:{count:count,id:id}, 
     success:function(data){ 
      // alert(data); 
      // console.log(data); 
      if (data == "0") { 
       alert("do not log in"); 
       $("#popup-box1").show(); 
      } 
      if (data == "1"){ 
       alert("already log in"); 
       $("#popup-box1").hide(); 
       // alert(); 
       count++; 
       $("span .count").text(count); 
      } 
     }   
    }); 
}); 
}); 

PHP:

<?php 
session_start(); 

if (!isset($_SESSION["id"])) { 

    echo "0"; 


}else{ 
    echo "1";// 
    // 
    $id= $_POST["id"]; 
    // 
    $userid = $_SESSION["id"]; 
    // 
    $conn = mysqli_connect("localhost", "root", "", "maroon5"); 

    // 
    $sql = " INSERT INTO fav (news_id, user_id) 
      VALUES ('$id', '$userid') "; 
    $res = mysqli_query($conn, $sql); 


} 
?> 
+0

你的代碼檢索的一部分從數據庫中計數並顯示給用戶? – JJJ

+0

將1添加到mysql行需要'UPDATE'。你很可能會覆蓋你的價值。 –

回答

0

但每次刷新頁面,計數變成0再次

因爲你的函數將只叫onclick

$(document).on("click", ".flag" ,function(){ 

你可能需要調用同樣的方法或刷新方法onload

0

最後,我解決this.I把這個

<?php 
    $conn = mysqli_connect("localhost", "root", "", "maroon5"); 

    $sql1 = " SELECT * FROM fav WHERE news_id=1 "; 
    $res1 = mysqli_query($conn, $sql1); 
    $nums = mysqli_num_rows($res1); 

    ?> 
    <div class="post-footer"> 
    <div class="flag"> 
    <span class="flag-wrapper"> 
    <a class="flag-action" href="#"> 
     <i class="fa fa-heart-o" ></i> 
     <?php 
      echo "<span class='count'>". $nums ."</span>"; 
      ?> 
      <!-- <span class="count">0</span> --> 
      <span class="flag-text" >Like this news post</span> 
    </a> 
    </span> 
     </div> 
    </div> 
    </article> 
    </div> 
    </div> 
相關問題