How to get the selected value from dropdown list and past it to sql query
i have two dropdown list box,first one is sales area contain different kind of alphabet which get from cookie,second dropdown staff name is to change according to the selected value from first dropdown. How can i manage to pass the selected option value to my sql query so that it can be change according to the selected sales area. This is the results that i want to get I insert my code to the snippet for easy to do edit and demonstration.
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("slct2").innerHTML=response;
}
});
<table >
<tr>
<td> Sales Area
<select name="Area" id="area" >
<?php
$sarea = explode(",",$_COOKIE['cooAreaCode']);
foreach($sarea as $item){
?>
<option value="<?php echo strtolower($item); ?>"><?php echo $item; ?></option>
<?php
}
?>
</select >
</td>
<?
$var = $_POST['Area'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$var'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
odbc_free_result($rs);
odbc_close($link);
?>
<td> Staff Name
<select id="slct2">
?>
</select>
</td>
<label class="form_field">Your selected <span id="aggregator_name"></span></label>
使用append在选择标签中添加选项标签还可以在第一个下拉菜单(“#area”)的更改事件中执行所有工作
$(document).ready(function(){
$("#area").change(function()
{
var val =$(this).val();
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
$("#clct2").append(response);
}
});
});
});
I'm not a fan of jQuery, so you'll need to convert my Javascript to your needs, but what you need is to capture an onchange event for the first drop down and use it to dynamically process the SQL for the second dropdown.
<script>
document.getElementById('area').onclick = function(){
var xmlhttp;
var formData = new FormData();
formData.append('area_value', this.value);
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText); // for DEBUGGING.
if(xmlhttp.responseText == 'false'){
alert(xmlhttp.responseText);
} else {
document.getElementById('slct2').innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("POST", 'build_slct2.php');
xmlhttp.send(formData);
xmlhttp.onerror = function () { console.error(xmlhttp.statusText); }
}
</script>
The build_slct2.php
script would use $_POST['area_value']
to create the desired SQL query, process the query, and build the <option></option>
list that will end up in the slct2
drop down. The build_slct2.php
file would simply echo
the new contents for slct2
.
上一篇: 避免不带参数的SQL注入