0

php file

<button id='submit' name='submit' ><h1>Schedule</h1></button>
<?php
      include 'dbres.php';
      if (isset($_POST['submit'])){
        $sql = "UPDATE reserved SET reserved = false WHERE reserved = true;";
        $res = mysqli_query($conn,$sql);
        echo'document.getElementById("submit").onclick = function() {
        this.textContent = "reserved";
        }';
      }
    ?>

I want the javascript code inside the php code to changes the text from submit to reserved. I have tested the javascript code and it works by itself, but doesn't seem to work in php.

  • 4
    JavaScript runs on the client, PHP on the server. The code runs in different places at different times. You simply can't do this. – Tangentially Perpendicular Jan 20 '21 at 20:16
  • 2
    Why do you need JavaScript for this? What not generate HTML based on the output of PHP? – Dharman Jan 20 '21 at 20:17
  • You should also make your PHP code only viewable/executable for the server. Move all your PHP into separate files and set proper permissions for them. – hewiefreeman Jan 20 '21 at 20:19
  • I could only find ways of changing html text using javascript. If I use PHP to check if the button has been clicked on I'm not sure I could change the text using html.@Dharman –  Jan 20 '21 at 20:34
  • @hewiefreeman do you want me to leave the javascript code in this file and have it reference a different php file? –  Jan 20 '21 at 20:58

1 Answers1

2

You cannot echo JS inside PHP, they are two separate languages. If you want to have the client run the JS, you can use the script tag:

echo '<script>
    document.getElementById("submit").onclick = function() {
        this.textContent = "reserved";
    }
</script>';
e9x
  • 170
  • 1
  • 4
  • Yeah I copied and pasted your code but it doesn't seem to be working since the text hasn't changed. –  Jan 20 '21 at 20:30
  • check devtools, are there any errors showing in console or was the `script` element added at all? – e9x Jan 20 '21 at 20:32
  • So this is the error I received in the console but it references a css file. ```Failed to load resource: the server responded with a status of 404 (Not Found)``` –  Jan 20 '21 at 20:42
  • make sure you put the `echo ' – e9x Jan 20 '21 at 20:47
  • This is the exact code: ``` document.getElementById("submit").onclick = function() { this.textContent = "reserved"; } '; } ?>```I am referring to after the button has been pressed. –  Jan 20 '21 at 20:52
  • This should function as intended, I see nothing wrong with it... – e9x Jan 20 '21 at 21:11
  • I think Tangentially Perpendicular is right javascript and PHP are not combinedable. –  Jan 20 '21 at 23:36