简体   繁体   中英

Problem in assigning js value to php variable

How can i assign a javascript value to a php variable,

This is what i want to do:

<?php
    $pag = echo "<script language ='javascript'>var pn =                 document.getElementById('t').value; 
            document.write(pn); </script>";


?> 

But getting error as: Parse error: syntax error, unexpected T_ECHO

or is there any other way to do, but i want to assign that valur to php variable. can somebody help here?

First, you can't give an "echo" to a variable. echo send a string or an information to the browser.

Then, you need to understand that Javascript is interpreted on the browser and PHP on the server.

It means, PHP can send variable to javascript (in an ugly and static way or with Ajax) but Javascript can't, unless you use it to change page sending the variable via GET or via AJAX.

Finally you should tell us what you need that for...

Javascript is client side, all PHP code is loaded by the server, before sending to the client. Thus, the only way to access JS variables in PHP is by setting a cookie in js, or by using AJAX

If you want to assign the value to a variable and then echo it out, use this code instead:

<?php
    $pag="<script language ='javascript'>var pn = document.getElementById('t').value; document.write(pn); </script>";
    echo($pag);

?> 

Edit

Looking back over your question it would be good if you could explain exactly what you're trying to achieve.

删除回显。您将分配给变量,而不输出任何内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM