0

I know the title sounds exactly like other questions asked about this, but I've checked about ten pages deep into Google on various searches and can't find an answer. I've seen a few answers on other stack overflow questions that look like it may come close but I'm not sure how to implement what they're saying.

Currently I have this script, but it fetches the whole page of data.php.

<script type = "text/javascript" src="jquery-3.2.1.min.js"></script>
<script type ="text/javascript">
    $(document).ready(function() {
        setInterval(function() {
            $('#show').load('data.php')
        }, 5000);
    });
</script>

Data.php is a page with a constantly changing list. I'm trying to get the list to update in real time, so my idea was to fetch it from another page. I'm not too familiar with Javascript since I'm more of a PHP/Python kind of guy. What I'd like it to do is append new DIVs from data.php or MySQL rows/JSON/whatever works, to the top of the list.

My problem with this is that it fetches the entire page, which is hard because some of the DIV's have media, which is a no go for refreshing the whole page. This code is also ridiculous because when you load the page up, it will show a blank white page until the it reaches the time shown. I'm just trying to have it append new DIVs with PHP generated code to the top of the page in real time, OR if I can somehow do it via MySQL or JSON I'm open to doing that as well. I'm not bad with PHP/MySQL/Python, but I'm new to JS if anyone can help. This is a personal project of mine but it's going to be for something that everyone can use online(for free). Thanks!

Mahbubul Islam
  • 998
  • 1
  • 10
  • 24
Jonathan
  • 21
  • 5
  • 4
    To do what you require you need to send a timestamp of the last request to the PHP code so that it can return only new items added since that date occurred. As such, your question is too broad for anyone here to help you effectively. You should also note that AJAX polling is generally considered a bad pattern to follow. If you need to keep the UI and server side data closely in sync I'd strongly suggest you research WebSockets or Server Side Events. – Rory McCrossan Aug 25 '17 at 08:34
  • https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist try to read this – Barclick Flores Velasquez Aug 25 '17 at 08:38
  • I already have a timestamp for each element. My issue is trying to figure out what exactly to do on the JS side of things. Is it broad to ask what exactly you mean by adding the timestamp element to the JS portion? – Jonathan Aug 25 '17 at 09:15
  • The comment from @RoryMcCrossan is correct. When you say "What to do on JS side" let's say you have a div and with each request to your ajax function you prepend the result - $( "#show" ).prepend( "
    Test
    " );
    – Carlos Alves Jorge Aug 25 '17 at 19:18

0 Answers0