This question already has an answer here:
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.
</div>
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.
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.