I have a table that includes the taxonomic name of a species. So there are separate columns for each species, domain, kingdom, phylum, etc. I am using a select boxes for each of these classifications, and what I need to happen is when the first one (Domain) is selected, the database is queried to get all the kingdomes where domain is the value of the previous select.
Here's what I have for my PHP in 'search.php':
<select name="domain" id="domain">
<option value="standard">-- Domain --</option>
<?php while($row = mysql_fetch_array($get_domains, MYSQL_NUM))
{
echo "<option value='$row[0]'>$row[0]</option>";
} ?>
</select>
<select name="kingdom" id="kingdom" >
<option value="standard">-- Kingdom --</option>
<?php
$result = array();
$domain = $_POST['domain'];
$get_kingdoms = mysql_query("SELECT DISTINCT sci_kingdom FROM tbl_lifedata WHERE sci_domain = $domain");
while($row = mysql_fetch_array($get_kingdoms, MYSQL_NUM))
{
$result[] = array(
'name' => $row[0]
);
}
echo json_encode($result);
?>
</select>
And this is what I have in my jquery:
$('#domain').change(function() {
$domain = $('#domain option:selected').val();
if ($domain == 'standard') {
$('#kingdom').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Domain:');
} else {
$('#kingdom').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
}
});
$('#kingdom').change(function() {
$kingdom = $('#kingdom option:selected').val();
if ($kingdom == 'standard') {
$('#domain').removeAttr('disabled', 'disabled');
$('#phylum').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
} else {
$('#domain').attr('disabled', 'disabled');
$('#phylum').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Phylum:');
$.post("search.php", {
'domain': option
}, function(data) {
var sel = $("#kingdom");
sel.empty();
for (var i = 0; i < data.length; i++) {
sel.append('<option>' + data[i].name + '</option>');
}
}, "json");
}
});
I'm having the most trouble understanding how the .post() function works. I know exactly what I want to do, just not exactly how to do.
My goal:
- obtain the value of the domain select box when it is changed
- use that value in the mysql query to get the relevant kingdoms
- execute the query using jquery and then populate the kingdom select box
Thanks!
Related
I'm hoping this is a simple solution. I am trying to make the first drop down determine the options available for the second. In my database, each flavor for the drink type has "type_id" column set as an integer (i.e. 1,2,3). The integers are meant to reflect the category in which they belong. Is it possible/make sense to base the available options for the second drop down off of the "type_id" that I determined?
I was hoping to accomplish this by using PHP, but I am not opposed to jQuery. I am not very well versed in one over the other. Thank you for your help in advance!
<?php
require "db-connect.php";
$dtype = "SELECT name FROM drinktype";
$typedata = mysqli_query($connection, $dtype);
echo "<select id='slctType'>";
if (mysqli_num_rows($typedata) > 0) {
while($row = mysqli_fetch_assoc($typedata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
$dflavor = "SELECT type_id,name FROM drinkflavor";
$flavordata = mysqli_query($connection, $dflavor);
echo "<select id='slctFlavor' ";
if (mysqli_num_rows($flavordata) > 0) {
while($row = mysqli_fetch_assoc($flavordata)) {
echo "<option value='{".$row['name']."}'>".$row['name']."</option>";
}
}
echo "</select>";
mysqli_close($connection);
?>
I have sample code for fetching the city according to their state. I have do that code with ajax, jquery and php. I think you have similar type of requirement. Please try below code concept for your requirement.
$(document).on('change','#state',function () {
$('#city').remove();
if($(this).val() != 'none')
{
var state_id = $(this).val();
$.ajax({
type: 'POST',
url: 'page.php',
data: { state_id: state_id },
success: function (city_response) {
if(city_response == '')
{
return false;
}
else
{
var city = '<select name="city" id="city" class="form-control">';
city += '<option value="-----">Please select any City</option>';
$.each(city_response, function (ck, cv) {
city += '<option value="' + cv['city_id'] + '">' + cv['city_name'] + '</option>';
});
city += '</select>';
$("#city_div").css('display', 'block');
$('#cities').append(city);
}
}
})
}
else
{
$("#city_div").css('display', 'none');
}
});
I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,
I am terribly failing with an ajax/jquery piece of code I am trying to learn in order to solve a predicament I have.
Below is my ajax:
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
$.post("addstudentsession.php",
{studenttextarea : search_val},
function(data){
if (data.length>0){
$("#studentselect").html(data);
}
});
At the moment I am keeping getting a blank page everytime I load my addstudentsession.php script. This is the only script I am working on so I am not sure if I am suppose to link the ajax to itself. But below is what I am trying to do:
I have a drop down menu below:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
<option value='21'>YANLO - 11-01-2013 - 09:00</option>
<option value='24'>YTMVB - 12-01-2013 - 03:00</option>
</select> </p>
Below I have a Multiple Select box where it displays a list of students that is taking the select assessment from the drop down menu above:
$studentactive = 1;
$currentstudentqry = "
SELECT
ss.SessionId, st.StudentId, st.StudentAlias, st.StudentForename, st.StudentSurname
FROM
Student_Session ss
INNER JOIN
Student st ON ss.StudentId = st.StudentId
WHERE
(ss.SessionId = ? and st.Active = ?)
ORDER BY st.StudentAlias
";
$currentstudentstmt=$mysqli->prepare($currentassessmentqry);
// You only need to call bind_param once
$currentstudentstmt->bind_param("ii",$sessionsdrop, $stuentactive);
// get result and assign variables (prefix with db)
$currentstudentstmt->execute();
$currentstudentstmt->bind_result($dbSessionId,$dbStudentId,$dbStudentAlias,$dbStudentForename.$dbStudentSurname);
$currentstudentstmt->store_result();
$studentnum = $currentstudentstmt->num_rows();
$studentSELECT = '<select name="studenttextarea" id="studentselect" size="6">'.PHP_EOL;
if($studentnum == 0){
$studentSELECT .= "<option disabled='disabled' class='red' value=''>No Students currently in this Assessment</option>";
}else{
while ( $currentstudentstmt->fetch() ) {
$studentSELECT .= sprintf("<option disabled='disabled' value='%s'>%s - %s s</option>", $dbStudentId, $dbStudentAlias, $dbStudentForename, $dbStudentSurname) . PHP_EOL;
}
}
$studentSELECT .= '</select>';
But I have a little problem, I need a way to be able to display the list of students in the select box when the user has selected an option from the drop down menu. The problem with the php code is that the page has to be submitted to find its results.
So that is why I am trying to use ajax to solve this but what am I doing badly wrong?
Try using ajax call as following,
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
XMLHttpRequestObject = false;
}
}
}
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "addstudentsession.php", true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
}
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4
&& XMLHttpRequestObject.status == 200) {
y = XMLHttpRequestObject.responseText;
$("#studentselect").html(y);
}
};
};
XMLHttpRequestObject.send("studenttextarea=" + search_val);
I have 2 drop-down menues. The first I populated with possible continents and want the second drop-down to what include all countries depending on the continent that was selected in the first menu. I have only 1 mysql table with columns: continent --> country. Currently there are all countries from all continents in the drop-down even when a continent was chosen. Thank you for your help!
Here is my code:
HTML
<input type="text" class="autosuggest" id="autosuggest2" placeholder="Select Country...">
<div class="country">
<ul class="result" id="result2"></ul>
</div>
<input type="text" class="autosuggest" id="autosuggest3" placeholder="Select Area...">
<div class="area">
<ul class="result" id="result3"></ul>
</div>
jQuery / Ajax
$(document).ready(function() {
$('#autosuggest1').keyup(function() {
var continent = $(this).attr('value');
$.post('php/dropdown.php', {continent:continent}, function(data) {
$('#result1').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest1').attr('value', result_value);
$('#result1').html('');
$('#result1').focusout('');
});
});
});
$('#autosuggest2').keyup(function() {
var country = $(this).attr('value');
$.post('php/dropdown.php', {country:country}, function(data) {
$('#result2').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest2').attr('value', result_value);
$('#result2').html('');
$('#result2').focusout('');
});
});
});
});
PHP
require_once '../connect/connectdropdown.php';
if (isset($_POST['continent']) == true && empty($_POST['continent']) == false) {
$continent = mysql_real_escape_string($_POST['continent']);
$query = mysql_query("SELECT DISTINCT `continent` FROM `area` WHERE `continent` LIKE '$continent%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['continent'], '</li>';
}
}
if (isset($_POST['country']) == true && empty($_POST['country']) == false) {
$country = mysql_real_escape_string($_POST['country']);
$query = mysql_query("SELECT DISTINCT `country` FROM `area` WHERE `country` LIKE '$country%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['country'], '</li>';
}
}
i wonder if you are still on this. Anyway a couple of things i would suggest:
Do only one query, pass it to json, and give it to javascript.
PHP
require_once '../connect/connectdropdown.php';
$id=0;
$result=array();
$query = mysql_query("SELECT * FROM `area` ");
while (($row = mysql_fetch_assoc($query)) !== false) {
$result[$id]=$row;
$id++;
}
echo json_encode($result);
Javascript
$(document).ready(function() {
var $mysqlData;
$.post('php/dropdown.php', {continent:continent}, function(data) {
//Json Data from server:
alert('JSON data: '+data)
//you can transform the data from PHP-Json to Javascript Object
$mysqlData = jQuery.parseJSON(data)
//now you can access your data like:
alert ('My first continent: '+$mysqlData[0].continent+' and it\'s first country: '+$mysqlData[0].country)
});
$('#autosuggest1').keyup(function() {
//Now you can use $mysqlData inside your logic
})
$('#autosuggest2').keyup(function() {
//You can use $mysqlData here too
})
});
i did not test this code, there might be some errors but that the logic i suggest you to take.
I have a page that lets people assign items to a category and javascript that lets user move as many items as desired from one box on left to one on right and back so that users can preview and fine tune choices (which end up in right box). It might be better if the items could be moved between lists instead of listboxes, but select box, I guess, is good for selecting uponclick. When user is done, I need to post items in right box to php script. However, am having trouble figuring out how to capture all the items in the right list. There is no form in the script so can't get it from document.form. Items are not really selected, they just populate list and I want to get them all. Is there a variable that has the whole list? Script is lengthy so here are functions that do work. Essentially I need a way to write out list of elements in right box at end. Thanks for any suggestions.
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {
if (listLeft.options.length == 0) {
alert('You have already assigned all items to the category');
return false;
} else {
var selectedItem = listLeft.options.selectedIndex;
move(listRight, listLeft.options[selectedItem].value, listLeft.options[selectedItem].text);
listLeft.remove(selectedItem);
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
} else if (side == 2) {
if (listRight.options.length == 0) {
alert('The list is empty');
return false;
} else {
var selectedItem = listRight.options.selectedIndex;
move(listLeft, listRight.options[selectedItem].value, listRight.options[selectedItem].text);
listRight.remove(selectedItem);
if (listRight.options.length > 0) {
listRight.options[0].selected = true;
}
}
}
}
function move(listBoxTo, optionValue, optionDisplayText) {
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
First, I think you have an error in your syntax. To get the value of the selected item of a select box, you would use something like:
var value = listLeft.options[listLeft.selectedIndex].value;
To write out all the options in a particular select box, you should be able to do something like this:
var options = document.getElementById('selectRight').options;
for (i=0; i<options.length(); i++)
document.write("value "+ i +" = "+ options[i].value);
I reworked your code a tiny bit and here is a complete working example:
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function showContents(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
alert("Option "+ options[i].value +" = "+ options[i].text);
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<button onclick="showContents('selectRight')">Show Contents</button>
</body>
</html>