-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");

7
  • global variable var name = '<?php echo $_POST["name"]; ?>'; Commented Apr 25, 2017 at 6:40
  • 1
    NO. You can use a global var at the php and that can be accessed at js file then. Commented Apr 25, 2017 at 6: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 <?php echo $_POST["name"]; ?> inside the html structure and taking that value/dom with e.g. query? Commented Apr 25, 2017 at 6:43
  • Possible duplicate of Include PHP inside JavaScript (.js) files Commented Apr 25, 2017 at 6:45
  • 1
    or stackoverflow.com/questions/9083089/… Commented Apr 25, 2017 at 6:46

2 Answers 2

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

3 Comments

Little modification - var name = '<?php echo $_POST["name"]; ?>';
thnx @mi6crazyheart
@Ivar hohoho! what a miss.
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

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.