Calling a PHP Method from JavaScript [closed]

2019-09-22 12:10发布

I was under the impression that since JavaScript is client-side and PHP is server-side, that it is impossible to call PHP from JavaScript; however, this code snippet works:

<script>
  function otherCourse(){
    var course = prompt("prompt?");
    document.write("
      <?php
        $con->query("INSERT INTO `Courses` (`Name`) VALUES ('blah')");
      ?>
    ");
  }
</script>

Why does this work? The entry was inserted into the database

2条回答
Juvenile、少年°
2楼-- · 2019-09-22 12:29

Your PHP is being executed from the server side. Your PHP that you've embedded in the JavaScript never actually ends up rendering anything.

Test it by removing any calls to the otherCourse function, and you'll see that the query still runs.

查看更多
再贱就再见
3楼-- · 2019-09-22 12:40

Your PHP executes on the server before that JavaScript even reaches the client.

查看更多
登录 后发表回答