alptureci
alptureci

Reputation: 5

refreshing the elements of html with javascript requesting data from php

I have a problem. I checked tons of good answers and tried them. Some helped me a lot but I still can't solve my problem completely. Can someone please help me?

I have one text file with following lines:

123456789, c
123456790, c
123456791, c
123456792, d

I read and parse this text file using a PHP script:

$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);

foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data); 

}

I can reach to the result of this php script with JS code below:

var userConStats = <?php echo json_encode( $myusers ) ?>;

for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}

with this; I filled the necessary html table for the first time. Everything is perfect.

The problem starts when I want this PHP to read text file every second and refresh the table elements according to the changes in the text file. PHP parse the text file only once and the changes in the text file won't change anything on the browser.

Maybe my approach to the problem was wrong I am not sure. Any help will be appreciated. Thank you! Complete code can be found below:

<?php

require 'connectionNetIndex2.php';
include 'txtPHP.php';
include 'userConStatUpdater.php'; 
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>2-NetIndex</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>

    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>MY_TEST</h1>



        <select name="OperationalMode">
            <option value="">Normal</option>
            <?php while($opMode = mysqli_fetch_assoc($opModes)) { ?>
                <option value="<?php  echo $opMode["operational_mode"];  ?>"><?php echo $opMode["operational_mode"]; ?></option>
            <?php } ?>
        </select>


    <?php if(isset($Users)): ?>
        <table>
            <tr>
                <td>IMSI</td>
                <td>Connection Status</td>
                <td>Profile</td>
            </tr>
            <?php  foreach($Users as $user):  ?>
            <tr>
                <td value="<?php echo $user["u_id"]; ?>"><?php echo $user["imsi"]; ?></td>
                <td id="<?php echo $user['imsi'];?>" class="conStats"></td>
                <td><form action="" method="POST">
                        <select id="profiles" name="Profiles" onchange="valueChanged()">
                            <option value="<?php echo $user["p_id"]; ?>"><?php echo $user["profile_name"]; ?></option>
                            <?php foreach($profiles as $PR): ?>
                                <option name="" value="<?php echo  $PR["p_id"]; ?>"><?php echo $PR["profile_name"]; ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input name="uid" type="hidden" value="<?php echo $user["u_id"]; ?>">
                        <!--<input type="submit" value="save">-->
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    <?php endif; ?>



    <script type="text/javascript">

        function conStatUpdater(){

            <?php

                    $myusers = array();

                    $my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
                    $rows = explode("\n",$my_txt);

                    foreach($rows as $row => $data){
                        $row_data = explode(',',$data);
                        array_push($myusers,$row_data); 
                        json_encode( $myusers ) ;
                    }
                ?>

            // pass PHP array to JavaScript array
            //Dont refresh the elements.
            var userConStats = <?php echo json_encode( $myusers ) ?>;

            //test is function working every second?
            //test result : YES
            console.log(userConStats[0][1]);


            for ( i = 0; i < userConStats.length-1; i++){
            document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];

            }
        }
        setInterval(conStatUpdater, 1000);

    </script>
</body>
</html>

Upvotes: 0

Views: 40

Answers (2)

Dr_Derp
Dr_Derp

Reputation: 870

Like you've realized, PHP can't update an HTML page after it's been generated (unless you reload the page). You can only do that with JavaScript. In order to get the data every second, you'd need to use ajax (https://www.w3schools.com/xml/ajax_intro.asp) to make asynchronous calls every second to your PHP page to get the data. So you'd need something like this:

PHP:

$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);

foreach($rows as $row => $data){
    $row_data = explode(',',$data);
    array_push($myusers,$row_data); 
}

print json_encode($myusers);

Your JavaScript code:

function updatePage(userConStats) {
    for ( i = 0; i < userConStats.length-1; i++){
        document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
    }
}

var secondPerRequest = 1;
setInterval(function() {
    $.ajax({
        url: "<your php page>",
        success: function(result) {
            var resultAsObject = JSON.parse(result);
            updatePage(resultAsObject);
        }
    });
}, secondsPerRequest * 1000);

Note that I used jQuery to do the ajax call because it's simpler that way. If you don't want to use jQuery, you can find info on how to do ajax in vanilla JS here: How to make an AJAX call without jQuery?

Upvotes: 1

bubjavier
bubjavier

Reputation: 1012

the <?php ... ?> block script inside your conStatUpdater() javascript function will not re-executed on the server-side because it is already parsed and will only yield the same result.

what you need is an AJAX function that will call your php script, in which that php script will re-executed on server-side and respond you with an updated values on your text files.

Upvotes: 0

Related Questions