我正在尝试通过下拉onchange事件更新会话值,并将此会话值用于第二页。为此,我添加了以下下拉列表和一个提交按钮。按下提交按钮我正在更新会话值。它正在工作,但大多数情况下,即使在更改下拉列表选项后它也会提供上一个会话值。它是错误的
<?php
session_start(); // start session before output
if( isset($_POST['submit']) ) { // some other page is posting to this page?
// save values from other page to session
$_SESSION['amount'] = $_POST['select_amount'];
}
?>
<form name="myForm" action="/thanks" method="POST">
<table> <tr> <td style="width:272px;">
<select name="select_amount" id="select_amount" onchange="submit()">
<option value="0">select a listing type</option>
<option value="10">Premium Listings </option>
<option value="20">Premium Blogs </option>
<option value="30">1 week sticky </option>
</select></td>
<td style="text-align:left;color:gray;"><span style="color:crimson;">*
</span>Select a listing type</td></tr> </table>
<table> <tr>
<input type="submit" name="submit" class="button_add" onsubmit="return
validateForm()">
</form>
答案 0 :(得分:1)
如果您想使用on change更改会话值,则无需表单提交,使用ajax然后您可以轻松完成
Step1 :像这样创建你的主文件
<?php
session_start(); // for show your session value
print_r($_SESSION); // remove this after check
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="myForm" action="/thanks" method="POST">
<table>
<tr>
<td style="width:272px;">
<select name="select_amount" id="select_amount" onchange="update_session_value(this.value)">
<option value="0">select a listing type</option>
<option value="10">Premium Listings</option>
<option value="20">Premium Blogs</option>
<option value="30">1 week sticky</option>
</select></td>
<td style="text-align:left;color:gray;">
<span style="color:crimson;">*
</span>Select a listing type
</td>
</tr>
</table>
<input type="submit" name="submit" class="button_add" onsubmit="return validateForm()">
</form>
<script>
function update_session_value(value) {
$.ajax({
type: "POST",
url: 'http://localhost/session.php', // change url as your
data: 'select_amount=' + value,
dataType: 'json',
success: function (data) {
}
});
}
</script>
然后创建简单的session.php文件
<?php
session_start();
if( isset($_POST['select_amount']) ) {
// save values from other page to session
$_SESSION['amount'] = $_POST['select_amount'];
}
?>
更改后刷新页面,您可以看到此结果
答案 1 :(得分:0)
对变更事件使用ajax调用
$("#select_amount").change(function(){
var select_amount = $("#select_amount option:selected").val();
$.post('change_session.php',{select_amount : 'store'},function(data){
if(data != ''){
alert(data);
}
});
});
将PHP脚本放在
上change_session.php