How should I access a variable from javascript in PHP to perform some actions?

Viewed 47

I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :

<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
  receiveMessage: function(fxn) {
    var callbackFunction = function(event) {
      if (typeof fxn === 'function') {
        fxn(event.data)
      }
    };
    document.addEventListener('message', callbackFunction, false);
    window.addEventListener('message', callbackFunction, false);
  }
}
</script>
</head>

<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
  value = message;
});
  
//sending the value with ajax
$.ajax({
  url : "./sample.php", //same file
  method : "GET",
  data: {"name": value},

  success : (res) => {
    console.log(value);
  },
  error : (res) => {
    console.log(res);
  }
})
</script>

<?php
echo $_GET['name'];
?>

</body>
</html>

The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?

Thanks! :)

1 Answers

Here's how you can access PHP code within in a <script> (without using AJAX):

<?php
echo"<script>";
  include ('javascriptStuff.js');
  echo'let x =  '.json_encode($phpVariable).';';
echo"</script>";
?>
Related