Come on, first, the PHP is a language Server-Side, that is, it is executed on the server, already the Javascript is Client-side, or seje, is executed on the client’s computer, everything occurs in the following order:
- The Server takes the file and interprets, translating everything to HTML, CSS and Javascript
- The Browser user displays the result of the previous 3 combined.
An example, you have the following code:
<?php
$strikes = 0;
?>
...
<script>
function increase() {
<?php $strikes++; ?>
}
</script>
What happens is that the Server first interprets the code, so when viewing the line
<?php $strikes++; ?>
He will execute it before sending the final result to the client, which will result in:
<?php
$strikes = 1;
?>
...
<script>
function increase() {
}
</script>
What you should do is create the session on another page, which is direct php, supposing this session is from a login, for example, you can send the Javascript information to the PHP of another page using the AJAX:
$.ajax({
type: 'POST',
url: 'login.php',
data: $("form").serialize(),
success: function(response) { ... },
});
This only works if you are in a php file and printing inside a tag
<script>
. Example:<script> var session = '<?php echo $_SESSION['NOME'];?>';</script>
– Karl Zillner
Java Script is a Client Side and PHP Server Side language. The code you placed is running on the client side, in which it does not interpret PHP code.
– Renato Junior
And by default
sesstion_start();
PHP must be at the beginning of the file before any code output.– Karl Zillner
You can use Javascript within PHP, but not PHP within Javascript. It won’t work. One will be interpreted on the server side, the other in the browser.
– Lucas de Carvalho