I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>
Related
I'm trying to auto populate some text fields (rate1 and rate2) based on a dropdown selection (instid and instfirstname). The values are all in one mysql table called tbl_insts. I'm trying the solution found in How to Get Content in text field dynamically, based on dropdown selection in php, but can't get it to work. Does anyone have any suggestions? Thanks in advance.
This is my mysql table called tbl_insts
instid instfirstname rate1 rate2
1 john 50 45
2 eric 25 45
This is my html form. I'm able to populate the dropdown correctly but not the text fields.
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
This is my code before the tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
This is my code in getrates.php in the same directory as the html file above.
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
try change data:{inst:inst} to data:{'inst':inst}
now you returning a string from getrates.php. From you code structure, you can do like this:
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1']."|".$res['rate2'];
}
}
..and
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
hope this helps.
Untested, but I think these changes should do the job.
while ($res = mysql_fetch_array($rec)) {
$result = [
'rate1' => $res['rate1'],
'rate2' => $res['rate2']
];
}
.......
die(json_encode($result));
and
success: function(data){
data = $.parseJSON(data);
$('#rate1').val(data.rate1);
$('#rate2').val(data.rate2);
}
Want to make a php program, where there will be a drop down which will contain some name of brands .. after selecting the " first drop down/ brands" products of the selected brand will show on another drop down.. need help . anyone ?
What you looking for is called a dependent select. It have barely nothing to do with php (except populating select options). I've found a demo for your case. You will need to install jquery to implement it in your code.
var $city = $(".city").on('change', function() {
$city.not(this).get(0).selectedIndex = this.selectedIndex;
});
You need to read about jQuery or CSS.
Look at this example (jQuery): http://dev7studios.com/dropit/
so you have to use ajax to do this
$(document).on("change","first select box",function(){
var id = $("first select box").val();
$.ajax({
url: "path to your file where you should write db code",
type: "POST",
dataType: "HTML",
async: false,
data: {"id": id},
success: function(data) {
$("second select box").html(data);
// here directly manipulate the data in controller or get the data in success function and manipulate .
}
});
})
in the file where you write db code
$a = "";
foreach(rows fro db as $a){
$a .= "<select value='db id'><?= name ?></select>";
}
echo $a;
we are capturing $a to out normal file add making that as the value for our second select box.
Hope it hlps
Use javascript function onchange select element and fetch records according to selected first select element value.
<form name="product" method="post" >
<select id="category" name="category" onChange="relodme()">
<option value=''></option>
<?php
$qry = "select * from category order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['category_id']?>" <? if($_POST['category'] == $arr['category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
<select id="Type" name="Type" >
<option value=''></option>
<?php
$qry = "select * from subcategory where category_id = '".$_POST['category']."' order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['sub_category_id']?>" <? if($_POST['Type'] == $arr['sub_category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
</form>
Javascript function:
function relodme()
{
document.forms[0].action="test1.php"; //your page name give here....
document.forms[0].submit();
}
I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my code right here, and if you figure out which part of the code is wrong, please point it out with a working example. Thank you.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
<?php
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "</select>";
echo "<div id = 'output'></div>";
?>
newtestx.php
<?php
$name = $_POST['name'];
echo $name."---";
?>
You need to change this line:
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"select\",\"name\",\"output\")'>";
1: Maybe you want to post the value. data:{select:$("select[name='name']").val()}.
But selector is false. tag is select not input.
`echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";";`
`data: { select: $(type+'[name='+theName+']').val()},`
2: .php will not get the param. Because your data's key is select, so $name = $_POST['select'];.
Finally, you want to return data, should use die($name);
`$name = $_POST['name'];
echo $name."---";`
After I created an if inside a SELECT tag (HTML) my browser keeps refreshing.
The purpose of this if is to make an OPTION selected when the condition appear.
I also have done this earlier on the same page and it worked.
My guess is that having the 2 SELECT dropdowns on the same page, having this code is making them to refresh each other (I have a jQuery to do onchange actions).
the code is this:
<select name="ddequipamento" id="ddequipamento" class="cliente" <? if (!$_GET['id']) echo "disabled" ?> >
<option value="---">---</option>
<?
if ($_GET['id'])
{
for ($i = 0; $i < $count_equipamento; $i++)
{
$idequipamento = mysql_result($result_equipamento,$i,"idequipamento");
$marca = mysql_result($result_equipamento,$i,"marca");
$tipo_equipamento = mysql_result($result_equipamento,$i,"tipo_equipamento.tipo_equipamento");
$num_serie = mysql_result($result_equipamento,$i,"num_serie");
echo (' <option value="'.$idequipamento .'" ');
if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
echo (' >'.$tipo_equipamento. ' - '. $marca . ' - '. $num_serie .'</option>');
}
}
?>
<option value="0" >Novo</option>
</select>
and the jQuery:
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val();
});
});
Please pass "eq" through URL , Please change it in script,
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val()+"&eq=<?php echo $_GET['eq'];?>";
});
});
If you want to "id" only then change in PHP part,
if ($_GET['id'] = $idequipamento){ //OLD if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
IF TWO DROPDOWNS WITH DIFFERENT ID "eq" and "id"
if you have 2 drop-downs use,
$(document).ready(function () {
$('#ddcliente').change(function () {
window.location.href = "index.php?id="+ $(this).val()+"&eq=<?php echo $_GET['eq'];?>";
});
$('#ddcliente2').change(function () { //CHANGE THE ID OF SECOND DROPDOWN
window.location.href = "index.php?eq="+ $(this).val()+"&id=<?php echo $_GET['id'];?>";
});
});
and also change the PHP part for 2 drop-downs
// FIRST DROP DOWN
if ($_GET['id'] = $idequipamento){ //OLD if ($_GET['id'] = $idequipamento){
echo (' selected="true" ');
}
// SECOND DROP DOWN , CHANGE VARIABLE NAME of $idequipamento2
if ($_GET['eg'] = $idequipamento2){ //OLD if ($_GET['eq'] = $idequipamento){
echo (' selected="true" ');
}
Hi All
I am working in a PHP project. I am stucked with an issue related with Ajax.
I have A select box for Company on whose selection department is displayed using ajax, and on selection of department from department select box along with another User group select box I get the list of users.
Now on change of User group I Send request to server using ajax as user group id and department id to fetch the respective users. But when I reselect the department I cannot get the new user list as this department list is generated from ajax and Ajax do not handle Javascript.
Code I Am Working With:
select box to select company
<select name="companyname" id="companyname" onchange="javascript:dochange(this.value);">
<option value="-1">-----Select Company-----</option>
<?php foreach($user_obj->getUserCompanyname() as $key => $value){
$selected = '';
if($value['company_id'] == $user_obj->user_company_id){
$selected = 'selected="selected"';
}
?>
<option value="<?php echo $value['company_id'];?>"
<?php echo $selected;?>><?php echo $value['company_name'];?></option>
<?php }?>
Javascript to execute ajax
<script>
//Inint_AJAX funnction is excluded as it has to do anything with requirement
function dochange(val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('selectdepartment').innerHTML="";
document.getElementById('selectdepartment').innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "company.php?val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
</script>
company.php
$val=$_GET['val'];
echo "<select name='departmentname' id='departmentname'>\n";
echo "<option value='-1'><b>Select Department</b></option>\n";
foreach($user_obj->getUserDepartmentname($val) as $k=>$vals){
echo "<option value='".$vals['department_id']."'>".$vals['department_name']."</option>";
}
echo "</select>\n<br>";
echo " <span class='asterisk>NOTE:Please (Re)Select the User Group everytime you change department.</span>";
User Group Select Box
<select name="usergroupname"
onchange="javascript:dochangereport(this.value,document.getElementById('departmentname').value);
dochangeoverride(this.value,document.getElementById('departmentname').value);" id="usergroupname">
<option value="-1">Select User Group</option>
<?php
foreach($user_obj->getUserGroupName() as $gkey=>$gval){
$gselect = '';
if($gval['usergroup_id'] == $user_obj->user_group_id){
$gselect = 'selected="selected"';
}
?>
<option value="<?php echo $gval['usergroup_id'];?>"
<?php echo $gselect;?>><?php echo $gval['usergroup_name'];?>
</option>
<?php }?>
</select>
function calling ajax call
<script>
function dochangereport(val,dep) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('selectreport').innerHTML="";
document.getElementById('selectreport').innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "reportto.php?val="+val+"&dep="+dep); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
</script>
**reportto.php**
$val=$_GET['val'];
$dep=$_GET['dep'];
echo "<select name='reportingto[]' multiple='multiple' size='3'>\n";
echo "<option value='-1'><b>Select Supervisor(s)</b></option>\n";
foreach($user_obj->getUserReportingto($val,$dep) as $rkey=>$rval){
echo "<option value='".$rval['user_id']."'>".$rval['user_fname']." ".$rval['user_fname']." </option>";
}echo "</select>\n";
could someone help me out in this?
I'm going to guess here: you are probably using something like
$('select.department').change(function() { (...ajax...)});
Instead, use:
$('select.department').live('change', function() { (...ajax...)});
This will also match any elements that are added later and match your jQuery selector. See also: http://api.jquery.com/live/.
EDIT:
Ok, so I guessed wrong. If you're not using jQuery, you will have to use event bubbling (http://www.quirksmode.org/js/events_order.html) (EDIT: apparently, onchange doesn't bubble in IE, see Does the onchange event propagate?) or add the event handler to the newly created <select> each time you update it, using
if (req.status==200) {
document.getElementById('selectreport').innerHTML="";
document.getElementById('selectreport').innerHTML=req.responseText; //retuen value
document.getElementById('reportingto').onchange = function() {
var val = this.value,
department = document.getElementById('departmentname').value;
dochangereport(val, department);
dochangeoverride(val, department);
}
}
And then add an id to your ajaxed selectbox, like this:
(reportto.php)
echo "<select id='reportingto' name='reportingto[]' multiple='multiple' size='3'>\n";
Good luck!
I found the other way round...
I Just changed the ajax caling functiona as
I just change the container ID to select box ID
function dochange(val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById('departmentname').innerHTML="";
document.getElementById('departmentname').innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "company.php?val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
And changed company.php file to
$val=$_GET['val'];
echo "<option value='-1'><b>Select Department</b></option>\n";
foreach($user_obj->getUserDepartmentname($val) as $k=>$vals){
echo "<option value='".$vals['department_id']."'>".$vals['department_name']."</option>";
}
And Hence gave me all required result..