Match php variable to a javascript variable

16

I'm trying to do something like this:

<script type="text/javascript">
    function guardar_alteracoes(){ 
        <?php
            $nome = ?>$('#nome').val();<?php;
        ?>
    }

</script>

That is, I want to give the value to a php variable from a textbox by javascript. The value of the text box arrives right here, but I can not match it.

    
asked by anonymous 11.07.2014 / 15:16

3 answers

18

PHP and JavaScript work at different times. PHP generates the page and from there there is only HTML and JavaScript. So it is not possible to match variables that belong to different worlds: server-side PHP and client-side JavaScript.

There are, however, two ways to communicate "between worlds." One of them, too defenitive for your case, is to make a form and pass the information with the page refresh.

The alternative you are looking for here is AJAX. A call / call on the server side where you can pass data and receive after a few milliseconds. An example would look like this:

$.ajax({
    type: "POST",
    url: "seuFicheiro.php",
    data: {nomeVariavel: 'valor variável',
    success: function (data) {
        // aqui pode usar o que o PHP retorna
    }
});

And on the PHP side something like:

$nome = $_POST['nomeVariavel'];
// correr outro código que precise...
echo $resposta;

This echo is what is passed to the client-side AJAX success function. Hope it helps you understand the mechanism.

    
11.07.2014 / 22:43
1

This is not possible. You could have javascript request an AJAX that would record the value in the session, and in the next run you would have this value.

Gambiarra alert!

    
11.07.2014 / 15:28
1

Using Javascript inline you can do something like this:

<script>
  var variavelJavascript = "<?php echo variavelPHP ?>";
</script>

But remember that depending on your needs, using AJAX is the most appropriate, as was said in the other answers.

See this question in Stack-EN

Update

Now I realized that you want to do the opposite, passing a JS variable to PHP. In this case only with AJAX or submit of a form .     

13.07.2014 / 16:23