问题描述:

I am making AJAX requests with a 10 second setInterval. The AJAX requests are calling a PHP file that selects records from the database and displays them as a notification to the user. My problem really is how to avoid displaying the same record at that 10s interval.

<script type="text/javascript">

setInterval(function(){

$.ajax({

type: "GET",

url: "getlinks.php",

success: function(data){

$("ul#notifications").append(data);

}

});

}, 10000);//time in milliseconds

</script>

My Getlinks.php File

<?php

$getNote = $db_con->prepare("select link FROM note WHERE user_id = ".$_SESSION['user']. "and now_id = 0");

$getNote->execute();

$rowNote = $getNote->fetch();

echo '<li>'.$rowNote['link'].'</li>';

?>

My problem is the AJAX keep selecting the same records every 10 seconds resulting in a long list of the same record.

网友答案:

Something I've done in APIs similar to this is to include a 'since' parameter.

So, your jquery GET function would end up looking like this.

$.get('getlinks.php', {since: last_id}, function() { //do stuff here });

And then your PHP script ends up looking something like this.

<?php
    $last_id = (isset($_REQUEST['since']) ? $_REQUEST['since'] : false);
    $sql = "select link FROM note WHERE user_id = ".$_SESSION['user']. "and now_id = 0" . ($last_id ? " AND id > $last_id;");
    $getNote = $db_con->prepare($sql);
    $getNote->execute();
    $rowNote = $getNote->fetch();
    echo '<li>'.$rowNote['link'].'</li>';
 ?>
网友答案:

As i understand you need to add a "displayed" field and a "read" field in the database. Update the displayed field when your ajax has been called, and the read field when the user really opened the note. I would use tinyint (1 = true, 0 = false) for the fields.

So your sql syntax for the popup "new note" need to be select link FROM note WHERE user_id = ".$_SESSION['user']. " AND now_id = 0 AND displayed=0.

I hope i understand your question right.

网友答案:

You can fix this with a small modification to your JS.

<script type="text/javascript">

 var old_data = '';

 setInterval(function(){
  $.ajax({
  type: "GET",
   url: "getlinks.php",
  success: function(data){ 
  if(data != old_data){
  $("ul#notifications").append(data);
  old_data = data;
  }

  }
 });
 }, 10000);//time in milliseconds 
</script>
相关阅读:
Top