-2

Can we do

var name = <?PHP $_POST["name" ?>

on .js file?

So I want to get the $_POST value of php to make use of it in my javascript, because php lack of document.getElementById("id");

  • global variable var name = ''; – JYoThI Apr 25 '17 at 06:40
  • 1
    NO. You can use a global var at the php and that can be accessed at js file then. – Jai Apr 25 '17 at 06:41
  • Do you want to work with `var name` later on or just want to include the `$_POST["name"]` into the dom? Why not just writing `` inside the html structure and taking that value/dom with e.g. query? – Nitro.de Apr 25 '17 at 06:43
  • Possible duplicate of [Include PHP inside JavaScript (.js) files](http://stackoverflow.com/questions/3241422/include-php-inside-javascript-js-files) – Ivar Apr 25 '17 at 06:45
  • 1
    or http://stackoverflow.com/questions/9083089/use-php-code-in-external-javascript-file – Ivar Apr 25 '17 at 06:46
  • or http://stackoverflow.com/questions/23574306/executing-php-code-inside-a-js-file – Ivar Apr 25 '17 at 06:46
  • or http://stackoverflow.com/questions/2928827/access-php-var-from-external-javascript-file – Ivar Apr 25 '17 at 06:47

2 Answers2

1

As i mentioned in the comment you can use a global variable to store the value and that variable can be used in the js file:

<html>
<head>
  <script>
    var name = '<?php echo $_POST["name"]; ?>'; // <---should be wrapped in quotes
  </script>
  <script src="jsfile.js"></script>
</head>
<body></body>
</html>

Now in the js file you can make a reference to this variable:

var user = name; // window.name;
Jai
  • 74,255
  • 12
  • 74
  • 103
0

no but you can make javascript file like javascript.php and put the following like on top of file

header("content-type: application/x-javascript");

and write javascript code in this file also then php code

Altaf Hussain
  • 181
  • 1
  • 9