Php Jquery Set Multiple selected values from database - php

I have three multiple select menus. I am trying to select the options returned from a database query. It is not setting any options. I console log the arrays returned by php and they are displayed as:["5233", "7148"]["5233", "5437", "5316"]["7029", "7852", "5525"].
I am not concerned about the form submission at this point. I only want to display the values returned from the db query as selected. I am sure there is something I am missing but can't seem to figure it out. I appreciate all the help I get. Thank you in advance!!
First are my 3 database arrays that are created:
Second is my html:
Third is my javascript/jQuery:
I have three multiple select menus. I am trying to select the options returned from a database query. It is not setting any options. I console log the arrays returned by php and they are displayed as:["5233", "7148"]["5233", "5437", "5316"]["7029", "7852", "5525"].
I am not concerned about the form submission at this point. I only want to display the values returned from the db query as selected. I am sure there is something I am missing but can't seem to figure it out. I appreciate all the help I get. Thank you in advance!!
First are my 3 database arrays that are created:
Second is my html:
Third is my javascript/jQuery:
<?
$huntNum = $hunts[$i][$fm_hunt_fields['__id']];
$cookRole = 'Cook';
$cookVols = get_volunteersByHunt($huntNum, $cookRole);
foreach ($cookVols as $cVols) {
//create new cook array that only contains ID of person
$exCooks[] = $cVols['_id_acct'];
}
$guideRole = 'Hunt Guide';
$hgVols = get_volunteersByHunt($huntNum, $guideRole);
foreach ($hgVols as $hVols) {
$exHg[] = $hVols['_id_acct'];
}
$supportRole = 'General Support';
$gsVols = get_volunteersByHunt($huntNum, $supportRole);
foreach ($gsVols as $gVols) {
$exGs[] = $gVols['_id_acct'];
}
?>
<script>
var existing_cooks = <?= json_encode($exCooks); ?>
var existing_hgs = <?= json_encode($exHg); ?>
var existing_gss = <?= json_encode($exGs); ?>
</script>
<form action="" name="vol-update" id="vol-update" class="vol- update" method="post">
<input type="hidden" id="id_hunt" name="id_hunt" value="<?= $huntNum; ?>" />
<input type="hidden" name="action2" id="action2" value="1" />
<table class="tyhp-account">
<tr>
<td>
<div class="floatL cont_lft_side">
<label for="cooks"><strong>Cooks</strong></label>
<select name="cook[]" class="form-control vCooks" multiple="multiple">
<?php
foreach ($cooksArray as $cook) {
?>
<option
<?
if (in_array($cook['ID'], $exCooks)) {
echo "selected='selected'";
}
?>
value="<?= $cook['ID']; ?>" >
<?= $cook['name_last'] . $cook['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
<td>
<div class="floatL cont_lft_side">
<label for="hunt_guides"><strong>Hunt Guides</strong></label>
<select name="huntGuide[]" class="form-control vHg" multiple="multiple">
<?php
foreach ($guidesArray as $guide) {
?>
<option
<?
if (in_array($guide['ID'], $exHg)) {
echo "selected='selected'";
}
?>
value="<?= $guide['ID']; ?>" >
<?= $guide['name_last'] . $guide['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
<?php
$allVols = getAllVolunteers();
?>
<td>
<div class="floatL cont_lft_side">
<label for="supp"><strong>General Support</strong></label>
<select name="gsupport[]" class="form-control vSupp" multiple="multiple">
<?php
foreach ($allVols as $allVol) {
?>
<option
<?
if (in_array($allVol['__id'], $exGs)) {
echo "selected='selected'";
}
?>
value="<?= $allVol['ID']; ?>" >
<?= $allVol['name_last'] . $allVol['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
</tr>
<tr>
<td> </td>
<td style="text-align:center">
<input type="submit" name="action" id="upVol" class="btn btn-primary" value="Update Volunteers">
</td>
<td> </td>
</tr>
</table>
</form>
//Volunteer information for hunts
<script>
var cooks = existing_cooks;
var hunt_guides = existing_hgs;
var gen_support = existing_gss;
console.log(cooks);
console.log(hunt_guides);
console.log(gen_support);
//Cooks multiSelect
$(".vCooks").val(cooks);
$('.vCooks').multiselect({
columns: 2,
placeholder: 'Select Cooks'
});
//Hunt Guide multi-select
$(".vHg").val(hunt_guides);
$('.vHg').multiselect({
columns: 2,
placeholder: 'Select Hunt Guides'
});
//General Support multi-select
$(".vSupp").val(gen_support);
$('.vSupp').multiselect({
columns: 2,
placeholder: 'Select General Support'
});
return false;
</script>

Related

Inserting values into database from form with drop downs

I'm trying to insert values input from the user in a form into my database.
I am trying to create 2 drop down lists, with the first deriving the options for the second. For example the first drop down list for Faculty, with the second drop-down list containing the schools within the selected faculty.
I am also then wanting to insert the gathered information into my database however I can focus on that after getting the drop-down's correct first.
My register page is on one page with the getSchool.php on a different file, I have a feeling the connection between the two could be my issue.
The register.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM faculty");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Faculty & School</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script>
function getFaculty(val) {
$.ajax({
type: "POST",
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
}
});
}
function selectFaculty(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Faculty:</label><br/>
<select name="faculty" id="facultyList" class="demoInputBox"
onChange="getFaculty(this.value);">
<option value="">Select Faculty</option>
<?php
foreach($results as $faculty) {
?>
<option value="<?php echo $faculty["facultyID"]; ?>"><?php echo
$faculty["facultyName"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
Below is the getSchool.php which gets all the schools
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
<?php
}
}
?>
Thanks in advance for any feedback and help.
Simon
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
Where is the #schoolList element ? Why getFaculty.php? Should it not be getSchool.php ?
First, just to re-iterate what was already mentioned, update your getFaculty() to get getSchool() and make sure it points to getSchool.php.
Now, you need to create a div following your first drop-down with an id schoolList.
<div class="row" id="schoolList"></div>
Now, update your getSchool.php so that it generates the full form/selection. Something along the lines of:
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<label>Schools:</label><br/>
<select name="schoolSelect" id="schoolSelect" class="demoInputBox">
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
Once you've got those ideas down, you'll have to make sure you have the full flow of your page the way you want it. Then follow similar standards for posting any inputs to the php page you use for database manipulation.
As noted in earlier posts, this solution still leaves you vulnerable to injection. That's for another post, another day.

keep selected values in select box field after search

I want to keep the selected values in select box after search .This is a vehicle search filter page and Page is coded using php and connected with database.
Database have 2 columns for both options that is driver age for 21-24 and driver_age for 25+ as some vehicles also available for both age of drivers
code below
<script>
$('#driver').change(function() {
if($('#driver option:selected').val() == '21-24') {
$('#driver').attr('name','driverage');
}
if($('#driver option:selected').val() == '25+') {
$('#driver').attr('name','driver_age');
}
});
</script>
<form id="myform" method="GET" action="">
<div class="fields">
<p>Vehicle Type</p>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<?php if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){ ?>
<option value="<?php echo $vt ?>" <?=isset($_GET['car_type'])&&$_GET['car_type']==$vt?'selected':'';?> ><?php echo $vt ?></option>
<?php }
} ?>
</select>
</div>
<div class="fields">
<p>Age of Youngest Driver</p>
<select class="half" id="driver" name="">
<option value="21-24">21-24</option>
<option value="25+">25+</option>
</select>
</div>
<input type="hidden" name="search" />
<div class="fields" style="text-align:center">
<input type="submit" value="Search" class="mitsub" />
</div>
</form>
Thanks and please help
You can add a conditional statement inside your foreach() that adds selected attribute to option. This will ensure that the selected value is selected in the list of options.
<?php
if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){
echo "<option value='$vt'";
if(isset($_GET['car_type']) && $_GET['car_type'] == $vt){
echo " selected";
}
echo ">$vt</option>\r\n";
}
}
?>
You can do this all in one, you just have to make sure the logic is correct.
echo "<option value='$vt'" . ((isset($_GET['car_type'] && $_GET['car_type'] == $vt) ? " selected" : "") . ">$vt</option>\r\n";
I just find it easier to work with a full if statement.

Updating a second dropdown after the first one has been chosen in javascript/php/html

I need an example that can let me populate the 2nd,3rd,...,7th dropdown list (all same entries) after the 1st dropdown list has been selected. I have all the values stored in an array in PHP before the HTML head.
I've looked at some examples, and couldnt find a specific solution
For example:
Let's say I have a warehouse full of franchisees and outlets under those aforementioned franchisees, I need to create order lists for 7 days ahead for that specific franchisee with n outlets. My solution was that the user/warehouse operator would pick a franchisee, then the 2nd (up to 7th) drop down list would have the outlets who are under that picked franchisee.
Thanks.
<?php
$productClass = new product();
$productClass->setProductList();
$franchiseeClass = new users();
$franchiseeClass->getAndSetAllFranchisees();
$franchiseeArray = $franchiseeClass->getUserList();
$operatorOutletClass = new users();
$operatorOutletClass->getAndSetUserByLevel("5");
?>
<html><head></head><body>
<div align="center">
<form name="BBOFranchisee" method="post" action="?" onSubmit="return checkSubmit()">
<table align="center" border="1">
<tr>
<td>
Franchisee:
</td>
<td colspan="8">
<select name="displayFranchisee" size="1" onChange="populateOutlet('findOutletByFranchisee.php?fid='+this.value)">
<option label="franchisees" value="0">--Choose Franchisee--</option>
<?php
for($i=0;$i<count($franchiseeArray);$i++)
{
foreach($franchiseeArray[$i] as $key => $val)
{
echo "<option label=\"franchisees\" value=\"$key\">$val</option>\n";
}
} ?>
</select>
</td>
</tr>
<tr>
<?php for($j=0;$j<7;$j++) { ?>
<td>
Outlet:
<select name="displayOutlet<?php echo $j; ?>" size="1">
<option label="outlets" value="0"> </option>
</select>
</td>
<?php } ?>
</tr>
</body>
</html>
I guess the continuation is the javascript part.. i tried to look at the solution that http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html provides, but it wont work with multiple drop downs.
In order to use that javascript example, you need to add an id to your 2nd-7th selects - id="displayOutlet<?php echo $j; ?>"
<?php for($j=0;$j<7;$j++) { ?>
<td>
Outlet:
<select name="displayOutlet<?php echo $j; ?>" id="displayOutlet<?php echo $j; ?>"size="1">
<option label="outlets" value="0"> </option>
</select>
</td>
<?php } ?>
Then in your javascript code, you can add a loop for the 2nd-7th selects.
if(req.status == 200) { // which represents ok status
for(var i=0;i<7;i++){
document.getElementById('displayOutlet'+i).innerHTML=req.responseText;
}
}

Search city for selected category

This ps_search.php page has dropdown for categories like laptop, bags etc... and a dropdown for city. if a user wants to post an ad means he/she wants to sell something on website , first of all a category is selected like laptop, bag or anything else. and then city is selected from where the ad is posted. if, for instance, a user posts an ad of laptop from city1 and we have no more ads of laptops from other cities . then after selecting laptop , city 1 should appear in a dropdown menu. i have two files ps_search.php ang get_city.php
//ps_search.php
<form name="search" method="post" action="<?php echo $base_url ?>search_rides.php?go">
<table width="100%" border="0" cellpadding="4" cellspacing="0" id="tbsrch-engine">
<tbody>
<tr>
<td height="61">
<strong>Choose Category:</strong>
</td>
<td>
<select name="category_id" id="category_id" style="width: 155px;" onChange="get_city(this.value,'<?php echo $base_url ?>dropdown/get_city.php')">
<option value="0">Any</option>
<?php $query = "SELECT category_id as id, category_name as name FROM tbl_ps_category ";
$result = mysql_query($query);
?>
<?php while ( $row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['id'].'-'.$row['name']; ?>"><?php echo $row['name']?></option>
<?php }?>
</select>
</td>
</tr>
<tr>
<td height="40">
<strong>City:</strong>
</td>
<td>
<div id="models">
<select name="city_id" id="city_id">
<option value="0">Any</option>
</select>
</div>
</td>
</tr>
<tr>
<td height="32"/>
<td>
<input type="submit" name="button2" id="button2" value="Search an Ad" class="fbutton"/>
</td>
</tr>
</tbody>
</table>
</form>
//get_city.php
<?php
include('../Connections/photohive.php');
$id = $_REQUEST['id'];
$explode = explode('-',$id);
$id = $explode[0];
$sql = "SELECT city_id FROM ".$ps_prefix."product WHERE category_id=".$id;
$query = mysql_query($sql);
//exit;
?>
<select name="city_id" id="city_id" style="width:155px;">
<option value="0">Any</option>
<?php
while ($row = mysql_fetch_array($query)){
$q1= sprintf("Select cityname from tbl_city where city_id='%s'" , mysql_real_escape_string($row['city_id']), " ORDER BY cityoreder ASC");
$r1= mysql_query($q1);
while($row2= mysql_fetch_assoc($r1))
{
?>
<option value="<?php echo $row['city_id']?>"><?php echo $row2['cityname']?></option>
<?php
}
}
?>
</select>
i have included js file as well
<script src="<?php echo $base_url;?>js/jquery.ajaxq-0.0.1.js" type="text/javascript"></script>
Please help me....
Your javascript should look like this:
(function ($) {
// When category select changes
$('#category_id').change(function() {
// make ajax query to get cities
$.get('get_city.php', {id: $(this).val())
.done(function(response) {
// get the cities dropdown from response and insert into page
$('#models').html(response);
});
});
})(jQuery);
I personally don't like returning HTML in my ajax calls. I usually prefer to return a JSON object and then parse out the HTML client side (usually using Handlebars). I think it's cleaner that way.

php drop down how to control the hide and show

i want to control the drop down box to control show or hide statement. I do like this but it seems it doesn't work, i have it working if im using radio button.
can help me with the code? which part am i wrong?
thank you.
$dbcnx = mysql_connect('localhost', 'root', '');
mysql_select_db('dbase');
if($_POST['gred'])$gred=$_POST['gred'];else $gred="";
<script language="JavaScript">
function funcHide(elemHide1,elemHide2,elemHide3)
{
document.getElementById(elemHide1).style.display = 'none';
document.getElementById(elemHide2).style.display = 'none';
document.getElementById(elemHide3).style.display = 'none';
document.getElementById(elemShow).style.visibility = 'visible';
}
function funcShow(elemShow1,elemShow2,elemShow3)
{
document.getElementById(elemShow1).style.display = 'block';
document.getElementById(elemShow2).style.display = 'block';
document.getElementById(elemShow3).style.display = 'block';
document.getElementById(elemShow1).style.visibility = 'visible';
document.getElementById(elemShow2).style.visibility = 'visible';
document.getElementById(elemShow3).style.visibility = 'visible';
}
</script>
<table>
<tr>
<td>Gred </td>
<td>:</td>
<td><select name="gred" id="gred">
<option value=""> </option>
<option value="A17" <?php if($gred=='A17')echo "selected";?> onClick="funcShow('box1', 'box2', 'box3');">A17</option>
<option value="A22" <?php if($gred=='A22')echo "selected";?>>A22</option>
<option value="A27" <?php if($gred=='A27')echo "selected";?>>A27</option>
</select>
</td>
</tr>
<tr>
<td>TK</td>
<td>:</td>
<td>
<select name="tk" id="tk">
<option value=""> </option>
<option value="01" <?php if($tk=='01')echo "selected";?>>01</option>
<option value="02" <?php if($tk=='02')echo "selected";?>>02</option>
<option value="03" <?php if($tk=='03')echo "selected";?>>03</option>
<option value="04" <?php if($tk=='04')echo "selected";?>>04</option>
<option value="05" <?php if($tk=='05')echo "selected";?>>05</option>
<option value="06" <?php if($tk=='06')echo "selected";?>>06</option>
</select>
<?} ?>
</td>
</tr>
<tr>
<td colspan="2" valign="top">Status</td>
<td valign="top">:</td>
<td>
<?php
$qry = "SELECT * from dtable where userid='".$USER->id."'";
$sql = mysql_query($qry);
$row = mysql_num_rows($sql);
if($row==0)
{
?>
<input type=radio name="status" <?php if($status=='retake') {?>checked="checked"<?php } ?> value="retake" onClick="funcShow('box1', 'box2', 'box3');">Retake<br /></tr> <tr>
<td colspan='2'>
<div id="box1" style="display: none;">Last Date <br> Latest Date<br>
</div></td>
<td><div id="box2" style="display: none;">: <br> : <br></div></td>
<td>
<div id="box3" style="display: none;">
<?php $rsu[lastdate] ?> <br> <?php $rsu[latestdate] ?>
</div>
</td>
don't put the onClick attribute onto the option tag. You should use onChange on the select tag and then pass in this.value. Then based on that value you can decide which "box" to show/hide. Just a simple example:
<script type="text/javascript">
function showHide(selValue){
switch(selValue){
case "A17":
//show/hide whatever box you want.
alert(selValue);
break;
default:
//do nothing
alert('nothing');
}
}
</script>
<select name="gred" id="gred" onChange="showHide(this.value);">
<option value=""> </option>
<option value="A17"<?php if($gred=='A17')echo "selected";?>>A17</option>
<option value="A22" <?php if($gred=='A22')echo "selected";?>>A22</option>
<option value="A27" <?php if($gred=='A27')echo "selected";?>>A27</option>
</select>
for now, as you can tell, it just alerts some values. But it is easy to change.
Use onChange to trigger JS when you change something in the dropdown menu, instead of onClick. With selectedIndex you can determine what has been selected (the option 'show' or 'hide') and go from there.
Tip: get rid of all the junk code and limit it to just the elements that you need. Try to make it work in its most basic form, then build it out to what you're actually trying to do. That way it's a lot easier to track bugs and find out why it's not working.
Also, you might want to look into jQuery. You can do pretty much the same in plain old JavaScript, but jQuery makes things like this a lot easier.

Categories