Home >Web Front-end >JS Tutorial >How Can I Pass JavaScript Variables to PHP for Server-Side Processing?
Passing JavaScript Variables to PHP Using Form Submission
To pass JavaScript variables to PHP, submitting a form with the desired variables as input values is a reliable method. PHP code cannot access variables directly from the client-side JavaScript code since PHP executes on the server.
Revised Code Example
Replace the existing code with the following:
<script type="text/javascript"> function func_load3(name) { var form = document.forms["myform"]; var selectBox = form.select3; var selectedOption = selectBox.options[selectBox.selectedIndex]; var selectedValue = selectedOption.value; var selectedText = selectedOption.text; // Set the hidden input value var hiddenInput = document.getElementById("hidden1"); hiddenInput.value = selectedValue; // Submit the form form.submit(); } </script> <form name="myform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <input type="hidden" name="hidden1">
PHP Code
<?php if (isset($_POST['hidden1'])) { $salarieid = $_POST['hidden1']; // Query the database based on the $salarieid variable } ?>
In this revised code:
The above is the detailed content of How Can I Pass JavaScript Variables to PHP for Server-Side Processing?. For more information, please follow other related articles on the PHP Chinese website!