Pass Java value to php

Asked

Viewed 830 times

0

I can’t pass the php value to Avascript this 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>

<?php
  
  session_start(); 
  
  $_SESSION['NOME'] = "João";
  
  echo $_SESSION['NOME'];
  
?>

  • 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>

  • 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.

  • 1

    And by default sesstion_start(); PHP must be at the beginning of the file before any code output.

  • 1

    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.

1 answer

3


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) { ... },
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.