问题
Is there a way to save the value of this dropdown list in a variable in PHP (no AJAX) without actually submitting the form?
<p>
Choose device type :
<?php
echo "<select name='device_type_id'>";
echo "<option value='Select'>Select</option>";
foreach ($dev_type_results as $row) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>"; ?>
</p>
回答1:
As far as I know, you cannot. Php generates your page, then the select method is implemented on the client's browser, not on the server (the server side php script is not running anymore). You need to submit the form and do another run of the php script, where you extract the value from the POST.
回答2:
Submitting a form, either through AJAX or directly, sends a request to the server side, in our case PHP.
If you want a server to receive any data, you need to submit the form.
The answer is NO. It's not possible with aforementioned restrictions.
回答3:
No. Not in PHP unless you submit it, save it in db and fetch it on different pages. In order to have values saved on the frontend, you'll have to use a store or state common in React or Vue. Another way is to use javascript to save in localstorage, cache storage, IndexDB or a cookie. You can then retrieve your value from there
回答4:
Simplest way to pass if you do not need the value on the server is sessionStorage if you do not need to save it across browser close or localStorage if you need longer storage
Page1:
$("[name=device_type_id]").on("change",function() {
sessionStorage.setItem("device_type",this.value);
});
Page2:
const deviceType = sessionStorage.getItem("device_type") || "Not passed";
回答5:
You can use cookie to save the data on client side then get it on server side.
PHP Code ( Server Side ):
if ($_COOKIE) {
header('content-type: text/plain; charset=utf-8');
print_r($_COOKIE);
exit;
}
Javascript Code ( Client Side ):
document.cookie = "name=yourname";
document.cookie = "favorite_food=bakso";
来源:https://stackoverflow.com/questions/61774227/how-to-save-value-of-dropdown-in-php-without-submitting