What are some common methods for transferring JavaScript variables to PHP in a form submission?

When transferring JavaScript variables to PHP in a form submission, one common method is to store the JavaScript variable in a hidden input field within the form. This way, when the form is submitted, the JavaScript variable will be included in the request and can be accessed in the PHP script handling the form submission.

// HTML form with a hidden input field to store the JavaScript variable
<form method="post" action="process_form.php">
    <input type="hidden" name="js_variable" id="js_variable">
    <!-- other form fields -->
    <input type="submit" value="Submit">
</form>

// JavaScript code to set the value of the hidden input field
<script>
    var jsVariable = "Hello from JavaScript";
    document.getElementById("js_variable").value = jsVariable;
</script>

// PHP script (process_form.php) to retrieve the JavaScript variable
<?php
$jsVariable = $_POST['js_variable'];
echo "JavaScript variable value: " . $jsVariable;
?>