开发者

jQuery prepend a auto fetch php file database

开发者 https://www.devze.com 2023-01-01 06:20 出处:网络
Currently i have a php file which fetch data from mysql to display in website. I\'m using input value to send as $_GET parameter to php file to determine the data to show.

Currently i have a php file which fetch data from mysql to display in website.

I'm using input value to send as $_GET parameter to php file to determine the data to show.

mysql_query("SELECT * FROM messages WHERE msg_id>'$refID' ORDER BY msg_id DESC");
//$refID is input value

So once it load,

i'm using th开发者_如何学编程is jquery code to display it on website

setInterval(
function ()
{
$.get('load.php?id='+refID, function(html) { 
  $("ol#update").prepend(html);
  $("ol#update li:first").slideDown("slow");
});
}, 10000);

My question is how do i stop it from keep on repeating the same message? i want it to display if there is new data.


If i have understood right, you want:

  1. add the new message if is not dupe;
  2. mantain the other unique messages

so you need to loop i think like this:

$.get('load.php?id=' + refID, function(html) {
    var check = false;
    $("ol#update li").each(function() {
        if (this.id == refID) check = true;
    });
    if (check == false) 
    $("ol#update").prepend('<li id="' + refID + '">' + html + '</li>');
    $("#" + refID).slideDown("slow");
});

Assuming you have

<ol id="update">
<li id="200">The Brown Fox Jump Over the Lazy Dog</li>
....
</ol>

and Assuming your HTML response come not included into a <LI> tag!


Update:

How does your response look like? The easiest way would be to update refID and set it to largest msg_id in your response. This way, you will always only get new data.

I would edit the PHP code that it produces HTML code in this format:

<li id="msg-msg_id"><div>user avatar </div><div> user posted msg</div></li> 

where you replace msg_id with the actual ID if the message (e.g. 200), e.g.

<li id="msg-200"><div>avatar</div><div>my message</div></li> 

Then you can do the following with jQuery:

$.get('load.php?id='+refID, function(html) {
  if(html) { // html will be empty (I guess?) if there are no new messages
      refID = $('<div>' + html + '</div>').find('li:first').attr('id').split('-',2)[1];
      $("ol#update").prepend(html);
      $("ol#update li:first").slideDown("slow");
  }
});

This will update refID to the ID of the currently retrieved message and the next time the functions gets executed it will retrieve the messages from this ID on.


(Old answer didn't help)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号