0

I know this may seem stupid, but I am just starting to learn both javascript and php. If I define a variable in javascript is it possible to use it in php? here is my example that I'm working with:

<p id="demo"></p>

<script>
function myFunction() {
 var text;
 var person = prompt("Please enter your name","");
    if (person != null){
        text = "Hello";
 } 
 if (person = null){
        text = "Error";
 } 
  document.getElementById('demo').innerHTML = text;
}

</script>
<button onclick="myFunction()">Try it</button>
<?php echo $person?>

I am trying to make it so that when they enter the name I can capture it as a php variable. And if they do not enter a name it gives an error message.

Mdrap
  • 9
  • 1
  • 1
    Why do you want to use php to display the name? Are you going to store it or is this just for display purposes? If so, you can use javascript to display the name. If you want to pass data to php I would recommend using ajax to post it to your server-side page *(php)* – NewToJS Jun 18 '15 at 01:27
  • Please [use the search](http://stackoverflow.com/search?q=%5Bjavascript%5D+%5Bphp%5D+send+variable+to+php) before you ask a new question. – Felix Kling Jun 18 '15 at 01:56

1 Answers1

0

Simple Answer

No

php - server side (executes on your server) JavaScript - Client Side (executes on every single client) [ignore NodeJS]

Because of this the server side php executes before the client even has the JS to execute.

Complex Answer

By using Ajax you could post anything from JavaScript to your PHP (server). This would allow you to submit forms or any other data.

Please note, that you should likely secure your API endpoints (PHP) with OAuth since you will be sending variables from the client and you can't trust the world.

abc123
  • 17,855
  • 7
  • 52
  • 82