How to add a javascript variable in PHP?

Asked

Viewed 1,253 times

1

I want to catch the variável of vetor that I believe in the JS and store its contents in one of the PHP.

<?php
       print("<SCRIPT language=javascript>  
              vetor_dados[$cont] ="text";
       </SCRIPT>"); 
$conteudo = vetor_dados;
?>

As I should?

Obs: The way to use the, ex:

<script type="text/javascript">
var x = 'valor';
</script>
<?php
    $x = "<script>document.write(x)</script>";
    echo $x;
?>

Causes the $x show <script>document.write(x)</script> and not the content of JS;

Image of how it appears as above: inserir a descrição da imagem aqui

2 answers

3


It is not possible like this. You need to understand the concept: HTML and JS are language client which means their execution is done on your computer. PHP is a server language, which means the PHP "engine" is on the server, not on your computer.

From a chronological point of view, the browser requests the page, the PHP engine parses the request and generates the code and sends it back to the browser, then PHP is terminated. The page travels through the internet, arrives at the user’s computer and from this moment the browser renders the received HTML and executes Javascript.

It means that the

 <?php $conteudo = vector_dados ?>

runs on the server, and the rest (HTML, CSS and JS) runs, AFTER, on the user’s machine.

To recover Javascript data with PHP, you need to re-upload the data to the server.

  • I mean @Peter, it’s not possible to run that way?

0

You’ll have to do it this way:

<SCRIPT language=javascript>  
    var vetor_dados ="text";
</SCRIPT>

<?php
    $conteudo = "<script>document.write(vetor_dados)</script>";

    echo $conteudo;
?>
  • So @Otto, as I put it in the edit, this way does not show the contents of the JS variable but the text: <script>document.write(vetor_dados)</script> which was assigned in PHP

  • I just ran the test here and it prints text and not <script>Document.write(vector_data)</script>

  • @Alexandre can perform the test

  • Yes @Otto, I just reissued the test and ended up giving the same! I will edit the post with an image showing!

  • Otto, in the case you put, the second part (PHP) will be executed BEFORE the first.

  • The funny thing is it works ....

  • Of course it works. You don’t even have to test...

Show 2 more comments

Browser other questions tagged

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