Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

javascript - How to read two files that can be updated without refreshing?

I don't know if I'm clear, but...

In summary, I'm a streamer and I'm doing a PHP website to show my socials media and my latest donations/followers on my OBS (Bad or good, that's not the question!). This is a slideshow HTML/JS page with PHP to read files (Because JS can't).

I have two files (most_recent_follower.txt and most_recent_donator.txt) which can be updated. I am able to read on these files and it works. But, the problem is that I'm not able to make that the last donator or the last follower updates without refreshing the page.

I tried the solution on this thread, but, it was not working. I have two files and it seems that PHP would only loop on one file... or I had bugs with JS, for example, if I write

clearstatcache(false, $file);

instead of

clearstatcache();

The output read ["Jean : 1.00$CAN (br tag)] instead of ["Jean : 1.00$CAN"] with the second function.

There is my code and a video of the actual output (I know that the optimisation is not quite good, my programming degree is far RN... lol!) '

<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Geekdan97 Stream Label</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
        
        <style>     
            @font-face {
                font-family: 'Rayman';
                src: url('../Font/rayman-webfont.woff2') format('woff2'),
                     url('../Font/rayman-webfont.woff') format('woff');
                font-weight: normal;
                font-style: normal;

            }
            
            body{
                font-family:"Rayman";
                color:white;
                text-shadow : 4px 4px black;
                vertical-align: middle;
                font-size:32px;
                background-color:black;
            }
            
            * {box-sizing: border-box;}
            .mySlides .mySlides2{display: none;}

            /* Slideshow container */
            .slideshow-container{
                max-width: 1000px;
                position: absolute;
                margin: auto;
                top: 13px;
                left : 30px;
            }
            
            
            .slideshow-container2{
                max-width: 1000px;
                position: absolute;
                margin: auto;
                top: 13px;
                left : 450px;
            }
            
            /* Fading animation */
            .fade {
              -webkit-animation-name: fade;
              -webkit-animation-duration: 3s;
              animation-name: fade;
              animation-duration: 3s;
            }

            @-webkit-keyframes fade {
              from {opacity: .4} 
              to {opacity: 1}
            }

            @keyframes fade {
              from {opacity: .4} 
              to {opacity: 1}
            }
        </style>
    </head>
    
    <body>
        <div>
            <img src="./images/bg.png" />
        </div>
        <div class="slideshow-container">

            <div class="mySlides fade">
                <img src="./images/facebook.png" width="35" height="35" style="float:left" /> &nbsp
                <div style="float:right">
                    Geekdan97 
                </div>
            </div>

            <div class="mySlides fade">
              <img src="./images/twitter.png" width="35" height="35" style="float:left" /> &nbsp
                <div style="float:right">
                    Geekdan97 
                </div>
            </div>

            <div class="mySlides fade">
              <img src="./images/twitch.png" width="35" height="35" style="float:left" /> &nbsp
                <div style="float:right">
                    Geekdan97 
                </div>
            </div>
            
            <div class="mySlides fade">
              <img src="./images/discord.png" width="35" height="35" style="float:left" /> &nbsp
                <div style="float:right">
                    !discord
                </div>
            </div>
        </div>
        
        <div class="slideshow-container2">
                    <div class="mySlides2 fade">
                            <img src="./images/donation.png" width="35" height="35" style="float:left" /> &nbsp
                            <div id="lastDonator" style="float:right"></div>
                    </div>

                    <div class="mySlides2 fade">
                            <div id="lastFollower"></div>
                    </div>
        </div>
        <br>
        <script>
            var slideIndex = 0;
            var slideIndex2 = 0;
                
            showSlides();
            showSlides2();
            getLastDonator();
            getLastFollower();
            
            function showSlides() {
              var i;
              var slides = document.getElementsByClassName("mySlides");
              for (i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";  
              }
              slideIndex++;
              if (slideIndex > slides.length) {slideIndex = 1}    

              setTimeout(showSlides, 3000);
              slides[slideIndex-1].style.display = "block";  
            }
            
            function showSlides2() {
                console.log("slide2");
              var i;
              var slides2 = document.getElementsByClassName("mySlides2");
              for (i = 0; i < slides2.length; i++) {
                slides2[i].style.display = "none";  
              }
              slideIndex2++;
              if (slideIndex2 > slides2.length) {slideIndex2 = 1}    

              slides2[slideIndex2-1].style.display = "block";  
              setTimeout(showSlides2, 4002);
            }
            
            //most_recent_donator.txt
            function getLastDonator(){                              
                var lastDonator = "<?php
                    $myfile = fopen("./labels/most_recent_donator.txt", "r");
                    echo fread($myfile,filesize("./labels/most_recent_Donator.txt"));
                    fclose($myfile);
                    
                    clearstatcache();
                ?>";
                $("#lastDonator").text("Last Donator : " + lastDonator);
                
                setTimeout(getLastDonator, 2000);
            }
            
            //most_recent_follower.txt
            function getLastFollower(){
                $("#lastFollower").text("Last Follower : " + "<?php
                    $myfile = fopen("./labels/most_recent_follower.txt", "r");
                    echo fread($myfile,filesize("./labels/most_recent_follower.txt"));
                    fclose($myfile);
                    
                    clearstatcache();
                ?>");
                
                setTimeout(getLastFollower, 2000);
            }
        </script>
    </body>
</html>
question from:https://stackoverflow.com/questions/65660512/how-to-read-two-files-that-can-be-updated-without-refreshing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After page loaded, the result of PHP script is output as string in the page (see: right click -> view-source), there is no mechanism in your JavaScript code asking PHP script to provide new data. As a result, PHP script will only run once when you access (e.g. refresh) the page.

You might need two files: one .php file that output the latest data, and one .html that constantly fetch data using JavaScript from api.php.

api.php:

<?php

$result = [
    'donator' => file_get_contents('./labels/most_recent_donator.txt'),
    'follower' => file_get_contents('./labels/most_recent_follower.txt'),
];

// output result as JSON format
header('Content-type: application/json;charset=utf-8');
echo json_encode($result);

// output: {"donator":"...", "follower":"..."}

index.html:

<!-- ... -->
<script>
    // ...
    async function updatePage() {
        let response = await fetch('./api.php');
        let data = await response.json();

        // output fetched data in debug console (in your browser: F12 -> console)
        console.log(data);

        $("#lastFollower").text("Last Follower : " + data.follower);
        $("#lastDonator").text("Last Donator : " + data.donator);
    }
    
    setInterval(updatePage, 2000);
    // ...
</script>
<!-- ... -->

I'm using the modern Fetch API and async in JavaScript to keep the code simple and clean.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...