Passing value from javaScript to php

0

I can not pass the value of php to javaScript really is that way?

var session = "<?php session_start(); $_SESSION['NOME'];?>"

alert(session);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><?phpsession_start();$_SESSION['NOME']="João";
  
  echo $_SESSION['NOME'];
  
?>
    
asked by anonymous 17.08.2017 / 20:12

1 answer

3

First of all, PHP is a Server-Side language, that is, it runs on the server, javaScript is Client-side , or seje, runs on the client computer, everything occurs in the following order:

    The Server takes the file and interprets, translating everything to HTML, CSS and JavaScript
  • The Browser of the user displays the result of the previous 3 combined.

For 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 you see the line

<?php $strikes++; ?>

It 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 to be a login, for example, you can send the JavaScript information to the PHP from another page using AJAX :

$.ajax({
  type: 'POST',
  url: 'login.php',
  data: $("form").serialize(),
  success: function(response) { ... },
});
    
17.08.2017 / 21:30