2

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! :)

3
  • I can't understand your overall architecture. What's the purpose of having a script that renders a complete HTML document, together with inline scripts, and then invokes itself via AJAX? You also say the code doesn't print anything—you're writing to the browser console, is there were you're looking? Commented Nov 2, 2020 at 17:04
  • @alvaro It actually meant that the echo statement in PHP didn't do anything. Commented Nov 2, 2020 at 17:52
  • 1
    Where are you expecting the output from the PHP code to show up? The only place it will show is in your browser's console, because you used console.log with the AJAX response. Commented Nov 2, 2020 at 19:05

1 Answer 1

1

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>";
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.