-2

Is this how you would pass a var from JS to PHP? or is there a better solution. Please could you help with the easiest and most efficient way.

<!DOCTYPE html>
<html>
<body>

<script>

var name="John Doe";

document.write(name + "<br>");

</script>

<?php

$name = <script>document.write(name);</script>

?>

</body>
</html>

I know this won't work, but how would I do it?

Bushell
  • 93
  • 2
  • 13
  • 4
    You misunderstand how PHP and JavaScript work. PHP runs on the server, JavaScript in the browser. What you want to do can't be done - you'd have to make an Ajax call to a separate PHP script to send it data from JavaScript – Pekka Mar 07 '13 at 10:14
  • You are asking for a better solution? This is not even a bad solution :) – Amberlamps Mar 07 '13 at 10:14
  • 1
    You can't because javascript is client side, PHP server side – Alessandro Minoccheri Mar 07 '13 at 10:14
  • 1
    it looks like you need a tutorial not an answer. – gdoron Mar 07 '13 at 10:14
  • Thats what I mean, what would be the best solution or any solution? – Bushell Mar 07 '13 at 10:15
  • 1
    There are literally hundreds of similar questions here on SO already, most of which have a useful answer on them. You would have been shown links to them while you were entering this question. A lot of them are also listed down the side panel of this page. Did you actually read any of them? – SDC Mar 07 '13 at 10:25

2 Answers2

3
<?php

$name = <script>document.write(name);</script>

?>

You can not do this

As php is a server side language and js client side,

First it run in server then it output to client were it executes js. So you can not pass values from js to php like in the code above.

If you want to do that you need to use AJAX.

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

please try this:

<?php
echo "<script language=\"javascript\">
     var name=\"John Doe\";
     document.write(name + \"<br>\");
     </script>";
?>

i hope this would be useful