Match php variable to javascript variable

Asked

Viewed 7,027 times

17

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 text box by javascript. The value of the text box comes right here, but I can’t match it.

  • 5

    Dude, it’s not possible to run PHP code inside Javascript code, first because it doesn’t compile, second, because javascript only runs in the browser, and PHP only on the server, for you to create communication between the browser and the server is needed first, establish a communication via Httpxmlrequest or Ajax through a POST

  • 1

    Since you are using jquery, use ajax to send/receive php values.

  • OK, I thought it might be possible. thanks anyway!

  • I found the tutorial below, just did not test to see if it works. http://www.mauricioprogramador.com.br/posts/passar-variavel-javascript-para-php

3 answers

20


PHP and Javascript work at different times. PHP generates the page and from there 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 defective for your case, is to make a form and pass the information with the refresh of the page.

The alternative you are looking for here is AJAX. A connection/call next to the server where you can pass data and receive after a few milliseconds. An example would be 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 AJAX Success function on the client side. I hope it helps to understand the mechanism.

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 asked in Stack-EN


Updating

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

  • 2

    The context calls for the opposite...

  • @Danielomine Now that I realized, I updated the answer, worth the warning. =)

0

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

Gambiarra alert!

  • OK, I thought it might be possible. thanks anyway!

Browser other questions tagged

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