just a quick one im looking to populate three drop down boxes to filter data and each one of them is going to affect the next.
what i want is for
Drop down 1 has company
once drop down 1 is selected the second drop down is populated with the branches for that company
once selected the third drop down is populated by the staff members for that company in that branch then when i press search it should pull the data for that 1 staff member. all of the information is in one table
the table i have is called "stafflist"
the columns are "company", "branch" and "staffname" each staff member has an autonumber id field which i use as a lookup called "staffID"
Thank you for any help
Regards
Slowie
Lets take an easy example, This is a javascript solution. I'm using this and it works perfectly fine. This script work in case if you select a country it populates its corresponding cities in the second dropdown. You can take some idea and use this for your case where you can deal with three dropdowns respectively.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure. In your case you have to create tables for company, branches and employees.
Hope this helps.
Have you ever heard about AJAX() OR jQuery ? if not then refer those link first; actually for your task you need to use Ajax OR jquery based dropdown boxes. which can make your dream success. :)
refer below link for your solution.
If any help needed you can feel free to ask me..
EDIT As per your commnet :
Step-1:- "SELECT company_id,company_name from company_table WHERE $condition ";
Step-2:- Fill first drop down box with record of first query set.
Step-3:- call jquery.ajax function onchange event of first drop down box in which call one
php page i.e: getRecords.php.
Step-4:- In getRecords.php page you need to get all the Branches of that company by passing company id in ajax and return a record array as response.
Step-5:- Fill second drop down with these records and again onchange event call another jquery.ajax request for final drop down box and do all things same as Step-4.
I think its all steps what you need for. still have any issue let me inform.
Thanks.
Related
I have two text box which is storing in database using AJAX. But I want to return back the new added row in table structure.
I am using this concept in add product to sell . when I want to add an item then it will be display in a tabular grid format.
This is my AJAX code.
var xmlHttp
function newVendorGridInital()
{
//alert("HI");
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{alert ("Browser does not support HTTP Request"); return }
var item= document.getElementById('itemcode').value;
var url="ajax_NewVendorGrid.php"
url=url+"?itm="+item; // For multiple value send.
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=newVendorGrid
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function newVendorGrid()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("GridRuntimeData").innerHTML=xmlHttp.responseText;
> > > I didn't understand how to target the id field > > > GridRuntimeData
}
}
In my html page I have created a table structure i.e. head part.
In my PHP file I am returning the entire inserted row in a html row format using echo statement.
<?php
echo "<tr><td>".$item."</td></tr>";
?>
and my doubt is how to show that row in table. If I write entire table structure in php code then it will be working fine. But i don't want do all the time to return entire row.
Please Help me.
You can dynamically add rows to a table with Javascript like this:
var table = document.getElementById("mytable");
var td = document.createElement('td');
td.innerHTML = 'new row';
var tr = document.createElement('tr');
tr.appendChild(td);
table.appendChild(tr);
jsFiddle demo here
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
I have two drop-down boxes. I want to populate second drop-down box on selection in the first drop-down box. My values are retrieving from database. Is this possible without using php or I need intermediate ajax and php file to get values from first drop-down and populate values file. Or this is possible without using php I mean only using Jquery. Please give me hint to do that.
Suppose I have 2 countries. First is INDIA and second is USA. ON first drop-down I am selecting countries and if first dropdown is selected than second dropdown populate its respective states.
if you encode your data into JSON format, then you can do something like this:
for HTML:
<select name='country' id='country'>
<option value='india'>India</option>
<option value='usa'>USA</option>
</select>
<select name='dates' id='dates'>
</select>
jQuery:
data = {
india: ['2011-03-11','2010-02-01'],
usa: ['2006-03-11','2009-02-01']
}
$('#country').change(function(){
var dateopts = ''
$.each(data[$(this).val()],function(i,v){
dateopts += "<option value='"+v+"'>"+v+"</option>"
})
$('#dates').html(dateopts)
})
Which when the country is changed, will build and populate the options for the second select box.
See the working example here: http://jsfiddle.net/xHxcD/
The above method requires all data to be sent to client side with the initial page request. If you have lots of data, it would be better to receive the data via AJAX. It would be simplest to do this by building an object in PHP with the same data structure as your client side, then use json_encode to convert it into as JSON string and echo it out.
Reading this into your client side would then be as simple as this:
$.ajax('myJsonData.php?country=india',function(jsonData){ data.india = jsonData })
You could do it either way. If you dont want to use ajax, just load every single option into an object. Then when you select something from select #1, populate #2 with the assoicated array of data from your object.
If I were doing it, I wouldn't do it with ajax unless there was a TON of data.
Yes you can do it without using php. For that you've to assign two different states list in Javascript array and base on the selection just change the options in the other select box. As simple as that.
You can assign the javascript array using your serverside scripting language while loading the page if you're using database to store the states.
But do not do this unless you've very small amount data. In your case you've only 2 countries so you can go ahead with it.
Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.
Reference to my answer: Cascade Dropdown List using jQuery/PHP
Hope this helps.
i'm still asking the same question regarding my drop downs.i have these two drop downs that sets the month and year respectively. the first drop down would allow the user to choose a month.if user would not choose any of the options the display would be the current month.same with the year drop down.i have already done it with a single drop down but i can't do it for two drop downs.scenario would be user could use from the month and let the year drop down to be in default and vice versa.
$(document).ready(function()
{
$("#months").change(function(event)
{
var m= $(this).val();
if(m!='00' || m!='NULL')
{
$("#memcount").load('../crd_reports/month.php', {"m":m});
$("#top10").load('../crd_reports/top10_monthly.php', {"m":m});
}
});
$("#years").change(function(event)
{
var y=$(this).val();
if( y == '10')
{
}
else if(y!='10' || y!='NULL')
{
$("#display").load('../crd_reports/month.php', {"y":y});
$("#top10").load('../crd_reports/top10_monthly.php', {"m":m});
}
});
});
this is my month.php. this file has the same content as the top10_monthly.php
if (isset($_REQUEST['m']))
{
$m = $_REQUEST['m'];
include '../../include/dbconnect.php';
$sql = "SELECT * FROM tbl_user WHERE admin_level LIKE 'CRD' ORDER BY id";
$result =mysql_query($sql);
It seems you want to set the date from the db to the page.Is it right?
If so , I think there is no need to do that , for you can just transfer the date value includes yeaer,month and day to the js by write php code in the js .
for example:
<script language="javascript">
var y=<?php echo $d['year']?>;
var m=<?php echo $d['month']?>;
var d=<?php echo $d['day']?>;
</script>
the $d is an array from the db. then you can use the jquery set the value to the drop down in the front html . But attenstion you should put the code in the $(function(){}).
Very simply, I have one dropdown menu dynamically populated with data:
SQL Code
$querycourse = "SELECT course, COUNT(course) AS count FROM acme WHERE course IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
PHP Code
echo "<select name='course[]' value='' multiple='multiple' size=10>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
What I need is another dropdown that is populated with data based on a selection from the first dropdown box.
I am using MySQL, PHP, Javascript and can also (at a push) use jQuery. I have no experience in Ajax.
Would anyone be kind enough to point me in the right direction?!
Thanks in advance, as always,
Homer.
First and Best Method (If you have or may have enough option specific data)
Use AJAX. It is the easiest way, I think, compared to the other ways to implement the same. Use Jquery to implement AJAX. It makes AJAX a piece of cake! Here I share my piece of cake for you -
Following is roughly the complete code you need -
Call a javascript function populateSecondDropdown() on your first select like this -
echo "<select name='course[]' value='' multiple='multiple' size=10 onchange='populateSecondDropdown(this, 'http://yourprojectUrl','Any Subject');'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
Define an ajax call inside inside the populateSecondDropdown() function -
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
function populateSecondDropdown(object,baseUrl)
{
$.ajax({
type: "POST",
url: baseUrl+"/ajax/fetchOptions.php",
data: { id_option: $(object).val(), operation: 'get_subjects' },
dataType: "json",
success: function(data)
{
//Clear options corresponding to earlier option of first dropdown
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data.subjects, function()
{
$('select#secondDropdown').append('<option value="'+$(this).attr('option_id')+'">'+$(this).attr('option_name')+'</option>');
});
$('select#secondDropdown').focus();
},
beforeSend: function()
{
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Loading...</option>');
},
error: function()
{
$('select#secondDropdown').attr('disabled', true);
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">No Options</option>');
}
});
}
</script>
And finally the query to fetch 2nd dropdown's options in the AJAX processor file fetchOptions.php. You can use $_POST['id_option'] here to fetch the options under it. The database query here should fetch the option_id and option_name fields for every option (as expected by the jquery code inside $.each) and return a json encoded array like this:-
return json_encode(array("subjects" => $resultOfQuery));
Second Method (Using only javascript)
Fetch all the data for the second dropdown grouped by the field of the first dropdown. E.g. let's take courses displayed in the first dropdown and subjects under courses displayed in the 2nd
Create all the options of the 2nd dropdown. Assign classes equal to the courses while creating the options like this:-
$querycourse = "SELECT course, subject FROM subjects WHERE subject IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
echo "<select name='subjects[]' value='' multiple='multiple' size=100>";
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value=\"$ntc[subject]\" class=\"$ntc[course]\">\"$ntc[subject]\"</option>";
}
echo "</select>";
Then define onchange="displaySubjectsUnderThisCourse(this);" for the first dropdown and write this javascript :-
function displaySubjectsUnderThisCourse(object)
{
var selectedCourse = $(object).val();
//Display the options with class = the selected option from first dropdown
$("."+selectedCourse).removeClass("hidden"); //define a class hidden with display:none;
$('option:not(.selectedCourse)').hide(); // hide all options whose class is other than selectedCourse - Not sure whether this will work or not, though
//Deselect any previous selections
//If single option selection is allowed
$('select#secondDropdown option').attr('selected', false);
// or following if multiple selection is allowed (needed for IE)
$('select#secondDropdown option').attr('selectedIndex', -1);
}
The basic idea here is to hide/display option groups but my code may have errors.
Finally, please note, the second method (fetching all the option values) would be better only if you have limited small amount of data and are very sure there will always be less data in future. But, since nobody can be so certain about the future, it is advisable to use the AJAX method always.
There are two methods:
First, you can load all choices for
the second select list into a
JavaScript array. When an option is
selected in the first select,
populate the second with the
appropriate options.
Second, you can use Ajax to make a
call to the server and fetch the
options for the second select based
on the choice of the first. The
server would then return a list of
options (one per line, tab delimited
is how I do it) that you parse and
use to populate the second select.
The first option is very fast and easy, but may take a while to load if you have a large list of options for the second select.
The second option is more complicated, but much more flexible.
Here's some Ajax code to get you started:
Create a request:
var HTTP_UNINITIALIZED = 0;
var HTTP_SETUP_NOTSENT = 1;
var HTTP_PROCESSING = 2;
var HTTP_PARTIAL_RESULT = 3;
var HTTP_COMPLETE = 4;
function createRequest()
{
var request = null;
try
{
request = new XMLHttpRequest();
}
catch( failed_once )
{
try
{
request = new ActiveXObject( "Msxml2.XMLHTTP" );
}
catch( failed_twice )
{
try
{
request = new ActiveXObject( "Microsoft.XMLHTTP" );
}
catch( failed_thrice )
{
request = null;
}
}
}
return( request );
}
Send the request:
var request = createRequest();
function doSearch( value )
{
getURL = "<url to get list>?Value=" + value;
request.open( "POST", getURL, true );
request.onreadystatechange = showResults;
request.send( null );
}
Use the results:
function showResults()
{
if( request.readyState == HTTP_COMPLETE && request.status == 200 )
{
if( request.responseText != "" )
{
var lines = request.responseText.split( "\n" );
for( i = 0 ; i < lines.length ; i++ )
{
var parts = lines[i].split( "\t" );
// populate the second select
}
}
}
}
How you handle the server side portion is up to you.