-2

I have JavaScript in my php file. It’s executed on timer. It displays counter by console.log() But my php code that I need to work doesn’t seem to be executed. I inserted there echo $Max_id;, but I don’t see in browser it printed. Neither do I see console.log($Max_id) in debug. Why is this?

Heres my script:

view_topic.php:

    <script>
    const CheckReload = (() => {
      let counter = - 40;
    
      
      return () => {
        <?php
        $tbl_name = fanswer;
        $sql7="SELECT MAX(a_id) AS Maxa_id FROM $tbl_name WHERE question_id='$id'";
        $result7=mysql_query($sql7);
        $rows7=mysql_fetch_array($result7);
    
        // if there no answer yet set it = 0 
        if ($rows7) {
            $Max_id = $rows['Maxa_id'];
        }
        else {
            $Max_id = 0;
        }
        console.log($Max_id); // cannot see it printed
        echo $Max_id;         // nor this
        
        if ($rows2['a_id'] < $Max_id)  {
            echo "location.reload();";
            console.log("location.reload();");
        }
        ?>
        counter++;
        return counter;
      };
    })();
    
    {
    const refreshId = setInterval(
      () => {
        const properID = CheckReload();
        console.log(properID);
        if (properID > 0) {
          clearInterval(refreshId);
        }
      },
      1000
    );
    }
    </script>
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
  • Where do you close the ` – Marcello Perri Oct 10 '20 at 23:32
  • @MarcelloPerri before `counter++` – evolutionxbox Oct 10 '20 at 23:32
  • 1
    **Warning:** `mysql_*` extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the [mysqli](https://www.php.net/manual/en/book.mysqli.php) or [PDO_MySQL](https://www.php.net/manual/en/book.pdo.php) extension should be used. See also the [MySQL API Overview](https://www.php.net/manual/en/mysqlinfo.api.choosing.php) for further help while choosing a MySQL API. – Dharman Oct 10 '20 at 23:44

1 Answers1

-1

First of all, remove the console.log in your PHP-Code, thats JavaScript and throws a 500 Error in PHP.

The problem is, PHP writes the echo in the HTML, in your case in your <script>-Tag.

So, JavaScript throws an error, because your debug-data is in your JavaScript-Code.

If you want to debug this, echo it outside the <script>-Tag.

Also, note that PHP is executed on the server and not after the page is loaded, so if you write PHP-Code in a JavaScript loop, it will be executed only on the page load and won't change later in the JavaScript loop.

HTTP-Requests

If you want to make a database request every few seconds, you have to make an http-request with JavaScript to a PHP-Script in your loop, so another PHP-File is executed every few seconds. You can create such an request easily with AJAX (jQuery).

EinLinuus
  • 625
  • 5
  • 16