简体   繁体   中英

How to save a value from javascript-generated data to PHP variable?

The reverse of this one:

<script>
document.getElementById("jscript_element").value = '<?=$php_variable?>';
</script>

Is it possible?

Note: Post/Get must not be used since the script will be integrated only in an onChange event, then the rest is history.

Thanks in advance!

You'll either have to write the value to an input with Javascript, and record the value when the form is posted, or use AJAX to send the value off to your server for processing. Once the page is loaded, PHP is done, period.

I think the answer to your question lies in the order in which the two types of script are interpreted.

document.getElementById("jscript_element").value = '<?=$php_variable?>';

Anything in the <? ?> <? ?> tags is interpreted by the server as PHP and then written to the page. This fully complete page is then transferred to the client. Note that the PHP only runs on the server.

Once the page is loaded and presented to the client, the PHP code does not exist. To set a PHP variable, you must transfer that data back to the server somehow.

You specify that you cannot use any type of Post or Get. Whether synchronously via a form action, or asynchronously via AJAX, any type of communication will fall under the category of either a Post or Get.

So, with that in mind:

Is it Possible?

No.

Although setting javascript generated data into a php variable is not directly possible, you can follow the below method to achieve this if required.

After getting the value that you want to be available in php, store the value in a cookie.

<script type="text/javascript">
generated_value=document.getElementById("jscript_element").value;
document.cookie="cookie_name="+generated_value;
</script>

Then in your php script just read the value from $_COOKIE array.

<?php $generated_value = $_COOKIE['cookie_name']; ?>

It will require a page reload, but you will be able to use the javascript generated value.

Behind your question there is, apparently, confusing between Server-Side actions, and Client-Side actions.

You should read some info about this subject, like this article: http://www.virtualshowrooms.co.za/articlepage.php?cp=101 .

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