2014-10-12 77 views
2

我想在不刷新它的情況下獲取表格中的最新post_id,但問題是每當用戶向數據庫中插入一個值時,它都會無限迴響最後一個post_id。我希望它只回聲一次。但我仍然想從表格中獲取最新的post_id。AJAX SET INTERVAL

這裏是我的主要PHP:

<div id = "this_div"> 
     <?php 
      include 'connect.php'; 
      session_start(); 
      $query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20"; 
      $execute_query = mysqli_query($con,$query); 
      while($row = mysqli_fetch_assoc($execute_query)) 
      { 
       $get_this_id = $row['post_id']; 
       echo $get_this_id."<br>"; 
      } 
      $_SESSION['get_this_id'] = $get_this_id; 
     ?> 
</div> 

這裏是我的jQuery的ajax:

<script> 
      var refreshId = setInterval(function(){ 
      compare_session = "<?php echo $_SESSION['get_this_id']; ?>"; 
       $.ajax({ 
       url: 'another_file.php', 
       data: {}, 
       success: function(data) 
       { 
        if(compare_session != data) 
        { 
         $('#this_div').text($('#this_div').text()+data); 
        } 
       } 
       }); 
      },400); 
</script> 

這裏的another_file.php

<?php 
    include 'connect.php'; 
    session_start(); 
    $query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1"; 
    $execute_query = mysqli_query($con,$query); 
    if($row = mysqli_fetch_assoc($execute_query)) 
    { 
    echo $get_this_id = $row['post_id']; 
    } 
?> 

回答

1

PHP代碼中你沒有更新變量compare_session,它總是保持初始值。所以在成功回調函數裏更新它

compare_session = "<?php echo $_SESSION['get_this_id']; ?>"; 
var refreshId = setInterval(function() { 
    $.ajax({ 
     url: 'another_file.php', 
     data: {}, 
     success: function (data) { 
      if (compare_session != data) { 
       $('#this_div').text($('#this_div').text() + data); 
      } 
      compare_session = data; 
     } 
    }); 
}, 400); 
+0

哇,謝謝sirrr !!!! :)) – 2014-10-12 14:16:45

+0

它的工作。我一直在試圖找出一個小時。 xD – 2014-10-12 14:17:22

+2

@monkeycoder:只是叫我pranav。 ...很高興幫助你.. – 2014-10-12 14:18:20