0

what am i missing?

i declare a variable in php:

<?php
$MyPHPStringVar = 'Hello World';
?>          

i have a form

 <form id="from1" action="someaction.php">
    <button>xy</button>
  </form>   

i have a javascript function in which i want to retrieve the declared php variable, but if i print it (var javaScriptVar), it returns the full

 "<?php echo $MyPHPStringVar; ?>"

what am i missing?

 <script>
 var javaScriptVar = "<?php echo $MyPHPStringVar; ?>";
    document.querySelector('#from1').addEventListener('submit', function(e) {
      var form = this;
      
      e.preventDefault();
      
      swal({
          title: "Are you sure?",
          text: javaScriptVar,
          icon: "warning",
          buttons: [
            'No, cancel it!',
        'Yes, I am sure!'
    })
...
...
...
</script>
  • 2
    Is your JS inside a `.php` file or an external `.js` file? (`` will only work in `.php` files, unless you tell your server otherwise) – brombeer Mar 25 '21 at 16:34
  • Take a look at [this post](https://stackoverflow.com/questions/65733674/how-to-give-php-variable-to-javascript) – Teemu Mar 25 '21 at 16:34
  • brombeer it is all in a php file – Martin Kuchen Mar 25 '21 at 16:37
  • View the source in the browser. Make sure it says `var javaScriptVar = "Hello World";`. PHP is processed before the page is sent to the browser, the javascript afterwards, so there's no mixing of the two in a situation like this. – aynber Mar 25 '21 at 16:43
  • 1
    *if i print it (var javaScriptVar), it returns the full* `""`? My guess, the file does not end in `.php`, or you dont have php installed – Lawrence Cherone Mar 25 '21 at 16:43
  • thanks for your help. i figured that you were right, the sandbox in which i run the code doesnt end in php... – Martin Kuchen Mar 25 '21 at 16:47

0 Answers0