Does PHP work within JavaScript?

1
<script language='Javascript'>
        function confirmacaoSair() { 
            var resposta = confirm('".$_SESSION['nome'].", tem que certeza que quer sair?');
            if (resposta == true) {
                unset({$_SESSION['nome']});
                unset({$_SESSION['matricula']});
                {session_destroy()};
                window.location.href = 'index.php';
            } 
        } 
</script>

This way it is not working, but my question is whether it works what I want to do.

    
asked by anonymous 01.12.2014 / 20:27

2 answers

5

No, what you're trying to do does not work.

The reason is that PHP is rendered on the server before the page is generated. After PHP finishes its processing, it is sent to the client browser, and there the javascript processing occurs.

What you're trying to do would require that PHP occur after javascript on the same request, and that's not possible.

The best solution to your problem is to redirect the page in javascript (change window.location ) to a page that the user is paging. On the server, PHP responds to the page that shifts by doing unset and redirecting to index.php .

    
01.12.2014 / 20:35
2

JavaScript runs on the browser while PHP code runs on the server. What you can try to do is to create JavaScript code while the page is being created by PHP.

One option is to print the values of the PHP variable in your JavaScript code at the time the page is created by PHP. Example:

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Source: link

    
01.12.2014 / 20:40