-1

I am planning to get the total number of visits to my site that I stored in the variable $total_visit in php, get the numerical value of this variable in javascript and put it in a moving counter. But when I call the value of the variable, my counter starts counting to infinity and exceeds the number of visits to my site.

The JavaScript code I wrote is as follows:

Start_Timer_one = 0;

var y = "<?php echo json_encode($total_visit); ?>";

function Counter1(oneN, TwoN) {
  document.getElementById(TwoN).innerHTML = Start_Timer_one++;

  Content_timer = setTimeout(function () {
    Counter1(oneN, TwoN);
  }, 1);

  if (Start_Timer_one > oneN) {
    clearTimeout(Content_timer);
  }
}
window.onload = Counter1(y, "test");

This is the php code I wrote to call the site statistics:


$time_zone = 12600;


$today = date("Y-m-d", time() + $time_zone);


$yesterday = date("Y-m-d", time() - 86400 + $time_zone);


$week_visit = 0;
$month_visit = 0;
$month_str = null;


$file_src = 'visit-stats.txt';
chmod($file_src, 0755);


$read_file = file_get_contents($file_src);
if (filesize($file_src) > 0 || $read_file != ''){
    $split_file = explode('|', $read_file);
    $modify = $split_file[31];
    
    if($modify != $today){
        $today_visit = 1;
        
        if($modify == $yesterday){
            $yesterday_visit = $split_file[0];
        } else{
            $yesterday_visit = 0;
        }
        
        $week_visit += $today_visit + $yesterday_visit;
        $month_visit += $today_visit + $yesterday_visit;
        
        for($i = 2; $i < 30; $i++) {
            $month_str .= $split_file[$i - 1];
            
            if($i < 29) {
                $month_str .= '|';
            }
            
            if($i < 8) {
                $week_visit += $split_file[$i - 1];
            }
            
            $month_visit += $split_file[$i - 1];
        }
        
        $total_visit = $split_file[30] + 1;
        $last_modify = $today;
    } 
    else{
        $today_visit = $split_file[0] + 1;
        $yesterday_visit = $split_file[1];
        $week_visit += $today_visit + $yesterday_visit;
        $month_visit += $today_visit + $yesterday_visit;
        
        for($i = 2; $i < 30; $i++) {
            $month_str .= $split_file[$i];
            
            if($i < 29) {
                $month_str .= '|';
            }
            
            if($i < 8) {
                $week_visit += $split_file[$i];
            }
            
            $month_visit += $split_file[$i];
        }
                            
        $total_visit = $split_file[30] + 1;
        $last_modify = $today;
    }
} 
else{
    $today_visit = 1;
    $yesterday_visit = 0;
    $week_visit = 1;
    $month_visit = 1;
    
    for($i = 2; $i < 30; $i++) {
        $month_str .= '0';
        
        if($i < 29) {
            $month_str .= '|';
        }
    }
    
    $total_visit = 1;
    $last_modify = $today; 
}


$file_src_handle = fopen($file_src, 'w+');
$visit_data = $today_visit . '|' . $yesterday_visit . '|' . $month_str . '|' . $total_visit . '|' . $last_modify;
fwrite($file_src_handle, $visit_data);
fclose($file_src_handle);


$config_array = array(
'user_time' => date("YmdHis", time() + $time_zone), 
'user_ip' => $_SERVER['REMOTE_ADDR'], 
'file_name' => 'visit-online.txt'
);
chmod($config_array['file_name'], 0755);


$online_file = file_get_contents($config_array['file_name']);


$online_file = explode("\r\n", $online_file);


foreach($online_file as $key=> $value){
    if(is_null($value) || $value == ''){
        unset($online_file[$key]);
    }
}


foreach($online_file as $key=> $value){
    $user_ip_time = explode("|", $value);
    if($user_ip_time[1] <= date("YmdHis", time() + $time_zone - 300)){
        unset($online_file[$key]);
    }
    
    if($user_ip_time[0] == $config_array['user_ip']){
        unset($online_file[$key]);
    }
}


$online = 1;
foreach($online_file as $online_users){
    $user_ip_time = explode("|", $online_users);
    if($user_ip_time[1] >= date("YmdHis", time() + $time_zone - 300)){
        $online++;
    }
}


$new_online = $config_array['user_ip'] . "|" . $config_array['user_time'] . "\r\n";
foreach($online_file as $key=> $value){
    $new_online .= $value . "\r\n";
}

          
$file_src_handle = fopen($config_array['file_name'], 'w+');
fwrite($file_src_handle, $new_online);
fclose($file_src_handle);


echo '<div class="visit-site text-center">
<div class="row">

<div class="col-xs-2 col-sm-2 visit-today">
<span id="visit-today" class="fas fa-user-check"></span><br>
today visit: <br>' . $today_visit . '
 </div>
 
 <div class="col-xs-2 col-sm-2 visit-yesterday">
 <span id="visit-today" class="fas fa-user-clock"></span><br>
yesterday visit:<br> ' . $yesterday_visit . '
</div>

<div class="col-xs-2 col-sm-2 visit-week">
<span id="visit-today" class="fas fa-user"></span><br>
week visit:<br> ' . $week_visit . '
</div>

<div class="col-xs-2 col-sm-2 visit-moon">
<span id="visit-today" class="fas fa-user-large"></span><br>
month visit:<br> ' . $month_visit . '
</div>

<div class="col-xs-2 col-sm-2 visit-total" id="visit-total">
<span id="visit-today" class="fas fa-eye"></span><br>
total visit :<br> ' . $total_visit . ' 
</div>

<div class="col-xs-2 col-sm-2 user-anline">
<span id="visit-today" class="fas fa-user-group"></span><br>
 online:<br> ' . $online . '
</div>

</div>
</div>
';    
?>

This code works correctly, but when I call the variables from the JavaScript side, the counter counts to infinity.

I put an image of the output of the above codes:

enter image description here

  • 3
    Not sure I can reproduce it - demo: https://jsfiddle.net/kg876e1a/ . But I guessed at a potential value for `y`. What output are you actually getting from `echo json_encode($total_visit);`? If it's just supposed to be a single number, why are you a) json_encoding it, and b) putting it inside quote marks as if it's a string? Neither is necessary. As mentioned above, json_encode may be adding extra quote marks as well, which could well cause problems. – ADyson Oct 18 '22 at 23:44
  • 3
    Your code works fine for me if I use e.g. `var y = 5` – Nick Oct 18 '22 at 23:45
  • Use your browser's _"View page source"_ option (right-click on the page) and check what value is actually set for `y` – Phil Oct 18 '22 at 23:48
  • you cannot store value at php to access in next access, PHP does not work that way. – Popeye Oct 18 '22 at 23:49
  • @Popeye true, but we don't actually know how `$total_visit` is being populated, so that may not be relevant. – ADyson Oct 18 '22 at 23:50
  • I tried different methods but still my counter exceeds the total number of visits. Please, if possible, edit my code so that it receives the numerical value of my PHP variable and my counter counts from zero until it reaches the variable number and does not go higher than that. Thanks a lot. –  Oct 18 '22 at 23:56
  • 2
    We told you how to fix it already - don't use quote marks, don't use json_encode, because it's only a number. But that's _assuming_ that $total_visit is correctly populated to begin with, which you haven't confirmed. Did you also do what we suggested and check what's actually being output? Then you'd probably see the mistake as well - i'd guess it looks something like `var y = "'30'";`, which ain't gonna work properly. – ADyson Oct 18 '22 at 23:58
  • 1
    `This is the php code I wrote to call the site statistics`....we don't really need to know, we just need to know what `echo json_encode($total_visit);` produced, and Phil told you how to find out. Try to address the actual specific requests made to you, rather than providing something different. Thanks. – ADyson Oct 19 '22 at 00:11
  • I tried this method and the answer was the same. I put the PHP code that I wrote to call the site statistics so that you can better understand what I mean. I want the site statistics to be displayed as a counter from zero to the main statistics. –  Oct 19 '22 at 00:17
  • 4
    First, just tell us what you're actually seeing in the source code of the rendered page in the `var y = "";` line. Then we'll understand whether it's worth bothering to look at that small mountain of PHP code or not. I don't understand why, after 30 minutes and multiple requests, you still haven't provided this simple but crucial piece of information, when it would only take you a few seconds to check. – ADyson Oct 19 '22 at 00:18
  • 4
    Here's some questions I'd like you to answer... Where is the JS code? Is it in a ` – Phil Oct 19 '22 at 00:25
  • 1
    _"I put an image of the output of the above codes"_... are you reading **any** of these comments? We cannot help you unless you actually read, understand and respond to the debugging requests we're making. If you need help understanding what we're asking, just ask for clarification but please stop adding unnecessary edits to your question – Phil Oct 19 '22 at 00:35
  • Again, no-one asked you for a screenshot of your page. We made a **very** specific request for a particular piece of information. Phil even told you **exactly** how to get the information we request, in [this comment](https://stackoverflow.com/questions/74118456/calling-the-php-variable-in-javascript-numerical-value-of-the-php-variable?noredirect=1#comment130863454_74118456), in case you were unsure what the process is. So why didn't you do that? Paying attention to detail is a crucial skill for a programmer - both when writing code and also gathering requirements, and following instructions! – ADyson Oct 19 '22 at 00:38
  • I changed the variable y in different ways. When I put a numeric value it works fine but when I put a PHP variable it counts to infinity. My js file is separate and when I get View page source, only the $total_visit variable value shows that it is correct, but in practice the counter counts to infinity and I also used eco. In the picture sent, you can see that the value of the counter is more than the number of views. My only question is, is there a way to call the numeric value of the $total_visit variable in javascript? –  Oct 19 '22 at 00:45
  • _"My js file is separate"_... and the penny drops. PHP does not operate on separate `.js` files. Does this answer your question? [Access PHP var from external javascript file](https://stackoverflow.com/a/2928844/283366) – Phil Oct 19 '22 at 00:46
  • `my JS file is separate`...well in that case, it does not execute PHP code, so your `y` variable will just be a string containing the raw PHP code, which is why it doesn't work. You'd have to move that definition into an inline script in the .php file, and pass it to the other JS (e.g. via a function call, or by using it as a global, like you do now). PHP code is only executed within `.php` files. – ADyson Oct 19 '22 at 00:47

1 Answers1

1

Quote from your comment:

my JS file is separate

...well in that case, it does not execute the PHP code, so your JS y variable will just be a string containing the raw PHP code, which is why it doesn't work as you expect.

You'd have to move that definition into an inline script in the .php file, and pass it to the other JS (e.g. via a function call, or by using it as a global, like you do now). PHP code is only executed within .php files.

N.B. Since you're expecting a number from the PHP variable, there's also no need to JSON-encode it or to enclose the output in quote marks in the JS - it's not a string, or a complex object.

E.g.

PHP file

<script>
  var y = <?php echo $total_visit; ?>;
</script>
<script src="yourJSFile.js"/>

JS File

Start_Timer_one = 0;

function Counter1(oneN, TwoN) {
  document.getElementById(TwoN).innerHTML = Start_Timer_one++;

  Content_timer = setTimeout(function () {
    Counter1(oneN, TwoN);
  }, 1);

  if (Start_Timer_one > oneN) {
    clearTimeout(Content_timer);
  }
}
window.onload = Counter1(y, "test");
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 1
    @Phil done, sorry - it's getting late here! – ADyson Oct 19 '22 at 00:53
  • 1
    Not meaning to discourage your fine work but there's a 12yo dupe target here ~ [Access PHP var from external javascript file](https://stackoverflow.com/q/2928827/283366) – Phil Oct 19 '22 at 00:54
  • @Phil fair enough, feel free to nominate it. I think I've added more explicitly that PHP isn't executed in a .js file, which I think the OP didn't know (although was perhaps slowly grasping towards the end :-)), so it perhaps has a little extra value too. – ADyson Oct 19 '22 at 00:56
  • Thank you very much for your guide, that was the problem and it was completely resolved. Many thanks –  Oct 19 '22 at 00:57
  • 1
    @programmer No worries. It would have been good to mention the detail about the separate JS file at the beginning, though :-). – ADyson Oct 19 '22 at 00:57
  • @ADyson I wasted my vote on a _"not reproducible"_ an hour ago – Phil Oct 19 '22 at 00:58
  • I'm sorry because I didn't think the problem was from here. Thank you very much for solving this big problem. –  Oct 19 '22 at 01:00
  • @programmer as well as the View Page Source looking at inline scripts, you can also click the links within it to get copies of the .js files as your browser is seeing them. So if you'd looked in there you'd have seen that the value of `y` was still the raw PHP string, and had not been executed by the server or turned into a number. That would have given you a clue about the issue. It's something to remember in future - you can check the raw output (or not!) of your PHP very easily, even if the main browser window hides it, or shows you something different. – ADyson Oct 19 '22 at 01:06