Does PHP work within Javascript?

Asked

Viewed 178 times

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’s not working, but my question is whether it works what I’m wanting to do.

  • 1

    Possible duplicate: http://answall.com/q/25136/129

  • Javascript runs in the browser while PHP code runs on the server. What you can try to do is create Javascript code while the page is being created by PHP. I’ve done this in Java (JSF). You should do it in PHP as well. See in my reply an example I copied from the OS in English. cc @Sergio

2 answers

6


No, what you’re trying to do doesn’t work.

The reason is that PHP is processed on the server before the page is generated. After PHP has finished processing, it is sent to the client’s browser, and there the javascript processing takes place.

What you are trying to do would require PHP to occur after javascript in the same request, and this is not possible.

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

2

Javascript runs in the browser while PHP code runs on the server. What you can try to do is 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 when the page is created by PHP. Example:

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

Source: https://stackoverflow.com/a/415885/1274092

Browser other questions tagged

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