473,395 Members | 2,253 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Controlled/Dependent Lists - for experts ;)

67
Hi

I'm now trying to have a dependent lists in a form

my form is a query based form

i.e. I fill my MySQL query from this form

I have around 30 fields/columns

each have number of values... sometimes 2 , sometimes 20.. maybe more !

I've searched the web to find a javascript code that helps me to do the dependent lists

I found few funtions.. but their work depends on INDEX !

they're very powerful functions.. i liked them.. but didn't know how to modify them until i get what i'm looking for

This is what I've found ( in two diff websites) - it's working if you copied it and pasted then tried it !
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function DepSelectOne(masterSelect){
  5.         var frm = masterSelect.form;
  6.         this.selectedBlock = 0;
  7.         this.selBoxes = new Array(masterSelect);
  8.         if((frm)&&(typeof Option != 'undefined')){
  9.                 for(var c = 1;c < arguments.length;c++){
  10.                         var selObj = frm[arguments[c]];
  11.                         if((selObj)&&(selObj.type.indexOf('select') == 0)&&(selObj.type.indexOf('mult') < 0)&&(selObj.options.length > 2)){
  12.                                 this.selBoxes[this.selBoxes.length] = frm[arguments[c]];
  13.                         }
  14.                 }
  15.                 if((this.selBoxes.length >1)&&(this.selBoxes.length == arguments.length)){
  16.                         this.selectElement = this.selBoxes[0];
  17.                         DepSelectOne.inst[this.index = this.selectElement.name] = this; //keep global record of this object instance.
  18.                         this.selBoxes[0] = this;
  19.                         this.optionBlock = new OptionBlock(0, this.selectElement, this.selectElement.options[0].value, this, 0);
  20.                         this.next = new DepSelectOneNext(this.selBoxes, 1);
  21.                         this.next.setSelection(this.optionBlock.getSelection());
  22.                         this.selectElement.onchange = new Function('DepSelectOne.inst[\''+this.index+'\'].handleChange(0)');
  23.                 }else{
  24.                         //alert('DepSelectOne constructor could not find\nsufficient properly configured SELECT elements\nto initialise.');
  25.                 }
  26.         }
  27. }
  28. DepSelectOne.inst = {}; //Globally accessible object to hold instances of the DepSelectOne Class.
  29. //call chain terminating functions.
  30. DepSelectOne.prototype.validateNext = DepSelectOne.prototype.reset = DepSelectOne.prototype.setSelection = DepSelectOne.prototype.setSelectedFromChild = function(){return true;}
  31. DepSelectOne.prototype.validate = function(){
  32.         return ((this.optionBlock.lastSelection < 0)?false:this.next.validateNext());
  33. }
  34. DepSelectOne.prototype.init = function(selectedBlock){
  35.         if(selectedBlock >= 0){
  36.                 this.optionBlock.lastSelection = selectedBlock;
  37.         }
  38.         if(this.optionBlock.lastSelection >= 0){
  39.                 this.optionBlock.doElement();
  40.                 if(window.setTimeout)setTimeout('DepSelectOne.inst[\''+this.index+'\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
  41.         }
  42. }
  43. DepSelectOne.prototype.handleChange = function(ind){
  44.         this.selBoxes[ind].changed();
  45.         if(window.setTimeout)setTimeout('DepSelectOne.inst[\''+this.index+'\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
  46. }
  47. DepSelectOne.prototype.refresh = function(){
  48.         this.selectElement.selectedIndex = this.optionBlock.lastSelection;
  49.         this.next.reset();
  50. }
  51. DepSelectOne.prototype.changed = function(){
  52.         this.optionBlock.readState();
  53.         this.next.setSelection(this.optionBlock.getSelection());
  54. }
  55.  
  56. function DepSelectOneNext(selBoxes, selBoxIndex){
  57.         this.selectedBlock = -1;
  58.         this.classObj = selBoxes[0];
  59.         this.previous = selBoxes[(selBoxIndex-1)]
  60.         this.selectElement = selBoxes[selBoxIndex];
  61.         selBoxes[selBoxIndex] = this;
  62.         this.selectElement.onchange = new Function('DepSelectOne.inst[\''+this.classObj.index+'\'].handleChange('+selBoxIndex+')');
  63.         this.seperatorOption = new DepOption(this.selectElement.options[0]);
  64.         this.optionBlocks = [];
  65.         var startIndex = 1;
  66.         while(startIndex < this.selectElement.options.length){
  67.                 var nextIndex = this.optionBlocks.length;
  68.                 this.optionBlocks[nextIndex] = new OptionBlock(startIndex, this.selectElement, this.selectElement.options[0].value, this, nextIndex);
  69.                 startIndex += this.optionBlocks[nextIndex].getOptionsTotal();
  70.         }
  71.         for(var cnt = 0,c = 0;c < this.optionBlocks.length;c++){
  72.                 this.optionBlocks[c].blockStart = cnt;
  73.                 cnt += this.optionBlocks[c].getItems();
  74.         }
  75.         if(++selBoxIndex < selBoxes.length){
  76.                 this.next = new DepSelectOneNext(selBoxes, selBoxIndex);
  77.         }else{
  78.                 this.next = this.classObj;
  79.                 this.previous.init(this.selectedBlock);
  80.         }
  81. }
  82. DepSelectOneNext.prototype.reset = function(){
  83.         if((this.selectedBlock >= 0)&&(this.optionBlocks[this.selectedBlock].lastSelection >= 0)){
  84.                 this.selectElement.selectedIndex = this.optionBlocks[this.selectedBlock].lastSelection;
  85.                 this.next.reset();
  86.         }
  87. }
  88. DepSelectOneNext.prototype.setSelection = function(selBlock){
  89.         this.selectedBlock = selBlock;
  90.         if(this.selectedBlock < 0){
  91.                 var opt = this.selectElement.options;
  92.                 opt.length = 0; //clear options
  93.                 opt[0] = this.seperatorOption.getOption();
  94.                 this.selectElement.selectedIndex = 0;
  95.                 this.next.setSelection(-1);
  96.         }else{
  97.                 var blk = this.optionBlocks[this.selectedBlock];
  98.                 blk.doElement();
  99.                 this.next.setSelection(blk.getSelection());
  100.         }
  101. }
  102. DepSelectOneNext.prototype.changed = function(){
  103.         if(this.selectedBlock >= 0){
  104.                 var blk = this.optionBlocks[this.selectedBlock];
  105.                 blk.readState();
  106.                 this.next.setSelection(blk.getSelection());
  107.         }
  108. }
  109. DepSelectOneNext.prototype.setSelectedFromChild = function(blockIndex){
  110.         if(this.selectedBlock < 0){     //only set from OptonBlock on the first attempt.
  111.                 this.selectedBlock = blockIndex;
  112.         }
  113. }
  114. DepSelectOneNext.prototype.init = function(selBlock){
  115.         if(selBlock >= 0){
  116.                 var blockIndex = 0;
  117.                 while(!this.optionBlocks[blockIndex++].nextBlockTest(selBlock));
  118.         }
  119.         this.previous.init(this.selectedBlock);
  120. }
  121. DepSelectOneNext.prototype.validateNext = function(){
  122.         return (((this.selectedBlock < 0)||(this.optionBlocks[this.selectedBlock].lastSelection < 0))?false:this.next.validateNext());
  123. }
  124.  
  125. function DepOption(optEl){
  126.         this.value = optEl.value;
  127.         this.text = optEl.text;
  128. }
  129. DepOption.prototype.getOption = function(){
  130.         return new Option(this.text, this.value);
  131. }
  132.  
  133. function OptionBlock(startIndex, selectElement, seperatorValue, owner, blockIndex){
  134.         this.blockStart = 0;
  135.         this.owner = owner;
  136.         this.index = blockIndex;
  137.         this.selectElement = selectElement;
  138.         this.seperators = [];
  139.         this.optionBlock = [];
  140.         this.lastSelection = -1;
  141.         var opts = this.selectElement.options;
  142.         while((startIndex < opts.length)&&(opts[startIndex].value == seperatorValue)){
  143.                 this.seperators[this.seperators.length] = new DepOption(opts[startIndex++]);
  144.         }
  145.         while((startIndex < opts.length)&&(opts[startIndex].value != seperatorValue)){
  146.                 if((this.lastSelection < 0)&&(opts[startIndex].selected == true)){
  147.                         this.lastSelection = this.optionBlock.length; //record first item selected, if any.
  148.                 }
  149.                 this.optionBlock[this.optionBlock.length] = new DepOption(opts[startIndex++]);
  150.         }
  151.         if(this.lastSelection >= 0)this.owner.setSelectedFromChild(this.index)
  152. }
  153. OptionBlock.prototype.getOptionsTotal = function(){
  154.         return (this.seperators.length + this.optionBlock.length);
  155. }
  156. OptionBlock.prototype.getItems = function(){
  157.         return this.optionBlock.length;
  158. }
  159. OptionBlock.prototype.nextBlockTest = function(selBlock){
  160.         if((selBlock >= this.blockStart)&&(selBlock < this.blockStart+this.optionBlock.length)){
  161.                 this.lastSelection = selBlock - this.blockStart;
  162.                 this.owner.selectedBlock = this.index;
  163.                 return true;
  164.         }
  165.         return false;
  166. }
  167. OptionBlock.prototype.getSelection = function(){
  168.         return ((this.lastSelection < 0)?-1:(this.blockStart+this.lastSelection));
  169. }
  170. OptionBlock.prototype.doElement = function(){
  171.         var opt = this.selectElement.options;
  172.         opt.length = 0; //clear options
  173.         if((this.lastSelection < 0)&&(this.seperators.length > 0)){
  174.                 opt[opt.length] = this.seperators[(this.seperators.length-1)].getOption();
  175.         }
  176.         for(var c = 0;c < this.optionBlock.length;c++){
  177.                 opt[opt.length] = this.optionBlock[c].getOption();
  178.         }
  179.         this.selectElement.selectedIndex = ((this.lastSelection < 0)?0:this.lastSelection);
  180. }
  181. OptionBlock.prototype.readState = function(){
  182.         if(this.lastSelection < 0){
  183.                 this.lastSelection = (this.selectElement.selectedIndex - 1);
  184.                 this.doElement();
  185.         }else{
  186.                 this.lastSelection = this.selectElement.selectedIndex;
  187.         }
  188. }
  189. </script>
  190. </head>
  191. <body onload="new DepSelectOne(document.forms['StateCityForm'].elements['State'], 'City');">
  192.  
  193. <form name="StateCityForm" ACTION="" METHOD="GET" TARGET="_blank">
  194.  
  195. First Choose State: &nbsp;
  196. <select name="State">
  197. <option value="choose">choose one</option>
  198. <option value="State_1">State 1</option>
  199. <option value="State_2">State 2</option>
  200. <option value="State_3">State 3</option>
  201. </select><br><br>
  202.  
  203. Now Select City: &nbsp;
  204. <select name="City">
  205. <option value="choose">&lt;select previous first</option>
  206. <option value="choose">select City for State_1</option>
  207. <option value="City_A__State_1" >City A of State 1</option>
  208. <option value="City_B__State_1" >City B of State 1</option>
  209. <option value="City_C__State_1" >City C of State 1</option>
  210. <option value="City_D__State_1" >City D of State 1</option>
  211. <option value="City_E__State_1" >City E of State 1</option>
  212. <option value="City_F__State_1" >City F of State 1</option>
  213.  
  214. <option value="choose">select City for State_2</option>
  215. <option value="City_A__State_2" >City A of State 2</option>
  216. <option value="City_B__State_2" >City B of State 2</option>
  217.  
  218. <option value="choose">select City for State_3</option>
  219. <option value="City_A__State_3" >City A of State 3</option>
  220. <option value="City_B__State_3" >City B of State 3</option>
  221. <option value="City_C__State_3" >City C of State 3</option>
  222. <option value="City_D__State_3" >City D of State 3</option>
  223. </select>
  224.  
  225. </form>
  226.  
  227. </body>
  228. </html>
  229.  
this above code - is done with index.. i can't list all of mysql table values !!

let me tell you what i would like to do:

in the options of first list their should be this code:
this code will show fields available in the mysql table
[php]
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]

NOW .. to show values of ONE field (second list)
i use this code:
[php]
<?
$sql = "Select filed2 FROM myTable GROUP BY filed2";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]

In the above code, what i want is to have field2 be different depending on what user has selected in the first list

is there something like !! .. if user select item in the first list - take this item and assign it to field ?? ( so I'll use in my above code $field instead of field2 ) !!!

please help me.. I feel i'm almost there finding the right solution for this problem.. but need some help from you guys :)

P.S.1. I don't want to submit twice in the form i.e. i don't wonna sumbit first list so second list should be assigned.. i've tried that and made some other problems in my form

P.S.2. I don't want to use AJAX - .. what i need is php/html/javascript

Thanks in advance :)
Aug 14 '07 #1
48 2315
code green
1,726 Expert 1GB
You are hacking somebody elses code to produce a solution in one go.
Fine if you know what you are doing.
Break this project into simple steps and solve each problem in turn.
You surely don't expect us to wade through this lot and make it work like you are expecting?
Aug 15 '07 #2
coool
67
well, I found this code in two places.. and they said there to readers to look at the webpage source - i.e. they gave the permission to do that

I posted the code here so you guys can understand easily what I'm talking about

this is not many problems together - it's only one problem called (controlled/dependent 2 lists) where what's selected in one list should be used in mysql query in the second list to get the values of the first list selection
Aug 15 '07 #3
pbmods
5,821 Expert 4TB
Heya, coool.

So the idea is to have two select elements, and when you select anything from the first select, the second select gets populated depending on what you picked. Does that sound right?
Aug 15 '07 #4
coool
67
yes that's exactly what I'm looking for..

similar to countries and cities -- if someone selects a country - then in the second list cities of that country should be shown only

in both select statements i should populate the options in a query similar to the last two portion of codes in my first post

but i don't want to submit twice in the form - and i don't want to use AJAX -- is there any other solution !! --- maybe some code in javascript can help !
Aug 15 '07 #5
coool
67
do you remember my thread called " Dynamic Condition "
==> http://www.thescripts.com/forum/thread691489.html

I'm actually wonna apply the controlled/dependent lists to that code

i.e. after choosing the field --- user will see in the next select statement only the values of that selected field (grouped by to have no duplicates

for fields:
[php]
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]

for values:
[php]
<?
$sql = "Select $field FROM myTable GROUP BY $field";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]
Aug 15 '07 #6
jx2
228 100+
"like countries and cities" so why you dont do it!!
[html]<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>simple document</title>
<script language='javascript'><!--

//================= generate in PHP =====================================
countries = new Array();
countries["usa"]= new Array("New York","Chicago");
countries["england"]= new Array("london","bristol");
//================= end of PHP generated script ===============================

function secondList(country){
var a = countries[country];
newListHTML='<select>';
for( city in a){
newListHTML+='<option value="'+a[city]+'">'+a[city]+'</option>';
}
newListHTML+='</select>';
document.getElementById('newListDiv').innerHTML= newListHTML;
}
-->
</script>
</head>
<body>
<form action="vartree.php" method='POST'>

<select name="firstList" onchange="secondList(this.value)">
<option value=''></option>
<option value='england'>england</option>
<option value='usa'>usa</option>
</select>
<div id='newListDiv'></div>
</form>
</body>
</html>[/html]
did you mean something like that?

regards
jx2
Aug 15 '07 #7
coool
67
your code depends on Arrays - but I can't put all of my fields with all of thier unique values in arrays because they are many - approx. of 30 fields with each have between 2 unique values and 50 unique values - maybe more !

so from your code - i've wrote some code - but it didn't work as I need to use the value of the first field in a php code (mysql for the second list)

[php]
<script language='javascript'>
function secondList(field)
{
newListHTML= '$sql = "SELECT 'field' FROM myTable GROUP BY 'field'"';
document.getElementById('newListDiv').innerHTML= newListHTML;
}
</script>
</head>

<body>

<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.value)">
<option value=''></option>
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>

<div id='newListDiv'>
<select>
<?
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
</div>
</form>
[/php]

what do you think ? can't this above code be fixed somehow !
Aug 15 '07 #8
jx2
228 100+
your code depends on Arrays - but I can't put all of my fields with all of thier unique values in arrays because they are many - approx. of 30 fields with each have between 2 unique values and 50 unique values - maybe more !
and? whats the problem? juzt use morte arrays :-)
[quoate[can't this above code be fixed somehow ![/quote]
yes it can be - honestly i think is almost done - i cant do it for you
1 u have to learn
2 i have no idea what you really need
3 i am not payed ;-)
4 i helped you as much as is needed

regards
jx2
Aug 15 '07 #9
pbmods
5,821 Expert 4TB
Heya, coool.

The thing about PHP is that it doesn't "talk" to the browser the way that JavaScript does.

The general flow of a web request is:
  • The browser sends a request to the server.
  • The server loads the requested page and decides what to do with it.
  • In the case of a PHP script, it runs the script by PHP and sends the result to the browser.
  • The server closes the completed request and then waits patiently for the next one.

Note that once the server sends the page to the client's browser, that's it; to get any more data from the server, you have to send a request for another page. This is the idea behind AJAX; it allows you to send a new request without having to load a new page.

If you want to be able to load a set of data without connecting to the server first, then you have to have loaded that data when you first opened the page. So for example, if you want to populate a select element from a MySQL result set, you have to either:
  • connect to the server again by using AJAX or submitting a form, or
  • have already loaded that data as part of the HTML / JavaScript.

This is what JX2 is trying to get at in his posts.

You can use PHP to format your MySQL result set as a JavaScript object and output that as part of the page.

For example:
Expand|Select|Wrap|Line Numbers
  1. $sql = "
  2. SELECT
  3.     DISTINCT
  4.         `countries`.`name`
  5.             AS `country`,
  6.         `cities`.`name`
  7.             AS `city`
  8.     FROM
  9.     (
  10.             `countries`
  11.         LEFT JOIN
  12.             `cities`
  13.                 USING
  14.                     (`countryid`)
  15.     )
  16.     ORDER BY
  17.         `countries`.`name` ASC,
  18.         `cities`.`name` ASC";
  19. $res = mysql_query($sql);
  20.  
  21. $data = array();
  22.  
  23. while($row = mysql_fetch_assoc($res))
  24. {
  25.     $data[$row['country']][] = $row['city'];
  26. }
  27.  
  28. echo json_encode($data);
  29.  
You end up with something very similar to what JX2 proposed as your output.

The other option would be to use AJAX (I promise it's not nearly as scary as it sounds!).
Aug 15 '07 #10
coool
67
okay from your useful comments :) I'm really near from the final correct solution

now i have a big Array that have all fields and inside this array i have a sub array for each field to present a unique values

my problem now with how to use 2-dim array in javascript

here's the code i reached unitl now:
Expand|Select|Wrap|Line Numbers
  1. <script language='javascript'>
  2.  
  3. function secondList(field)
  4. {
  5.         var value;
  6.         var content = new Array();
  7.         content =  data[field][];
  8.         newListHTML='<select>';
  9.         for(value in content)
  10.         {
  11.             newListHTML+='<option value="'+content[value]+'">'+content[value]+'</option>';
  12.         }
  13.         newListHTML+='</select>';
  14.         document.getElementById('newListDiv').innerHTML= newListHTML;
  15. }
  16. </script>
  17.  
here's how the data look like of my array:
array name: $data[][]
Expand|Select|Wrap|Line Numbers
  1. Array
  2. (
  3.  
  4.     [field1] => Array
  5.         (
  6.             [0] => value1
  7.             [1] => value2
  8.         )
  9.     [field2] => Array
  10.         (
  11.             [0] => value1
  12.             [1] => value1
  13.             [2] => value1
  14.             [3] => value1
  15.             [4] => value1
  16.         )
  17. .....................................................etc
  18. }
I can't get the javascript array working ! .. do you have any clue where is my mistake in the code ? !
Aug 15 '07 #11
pbmods
5,821 Expert 4TB
Heya, coool.

Where do you create the JavaScript data object?
Aug 15 '07 #12
coool
67
Oh ! --- should i create it inside my javascript !! how !

data is here inside the php code:

[php]
$sql1 = "SHOW FIELDS FROM TableOne";
$res1 = mysql_query($sql1);
$data = array();

while($row1 = mysql_fetch_row($res1))
{
$sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
$res2 = mysql_query($sql2);
while($row2 = mysql_fetch_row($res2))
{
$data[$row1[0]][] = $row2[0];
}
}
[/php]

when I do this:
[php]
echo "<pre>";
print_r($data);
echo "</pre>";
[/php]
,I get this output:
Expand|Select|Wrap|Line Numbers
  1. Array
  2. (
  3.     [field1] => Array
  4.         (
  5.             [0] => value1
  6.             [1] => value2
  7.         )
  8.     [field2] => Array
  9.         (
  10.             [0] => value1
  11.             [1] => value1
  12.             [2] => value1
  13.             [3] => value1
  14.             [4] => value1
  15.         )
  16. ..................................................  ...etc
  17. }
  18.  
Aug 15 '07 #13
coool
67
i looked at jx2 code !

when he/she created countries array, he didn't declare it inside the javascript !

similar to this , i've created " data " in php and then used it in javascript !

am i wrong :) ?
Aug 15 '07 #14
jx2
228 100+
i looked at jx2 code !

when he/she created countries array, he didn't declare it inside the javascript !

similar to this , i've created " data " in php and then used it in javascript !

am i wrong :) ?
i am HE :-)
you are wrong
i did declare array in javascript
and expected that you create this javascript/arrays in php (in php you can create dynamicly javascript code)

but lets be honest as PBmods sugested thats the job for ajax (to be honest thats the simliest and niciest solution in this case)

jx2
Aug 15 '07 #15
coool
67
oops

when jx2 wrote inside his javascript portion this:
Expand|Select|Wrap|Line Numbers
  1. //=================    generate in PHP =====================================
  2.     countries = new Array();
  3.     countries["usa"]= new Array("New York","Chicago");
  4.     countries["england"]= new Array("london","bristol");
  5. //================= end of PHP generated script ===============================
  6.  
it's written: generate in PHP --- so I thought that means these three lines should be generated in PHP not in javascript code

or !! i don't know what does jx2 mean !?
Aug 15 '07 #16
coool
67
Mr. HE :-)

thanks for explaning

I'm still afraid of AJAX !

can we do it together here ! or should i just stick with trying to solve this code i have until now !!!

Cheers,

SHE :-)
Aug 15 '07 #17
jx2
228 100+
lets be honest its seems you trying to do to much things at a time

if i were you i woul write php/mysql first
one function at a time okey? promise me you re going to learn and we can start
first of all how your table in mysql look like?
Aug 15 '07 #18
coool
67
:-)

my tables are just the same - same fields - no keys - we don't need to worry about that - and lets concentrate on doing the code for only one table

my form is a query based form - i'm asking the user to fill my query
and the problem here i'm trying to solve is to have a condition/criteria for my query

SELECT $fields FROM $table WHERE $criteria

after WHERE -- we usually have the name of the field then the operator then the value

now ! i know how to populate the fields i have in my table
with this code:
[php]
<select>
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
[/php]

and I know how to populate the values of one field - if my $field=field2 - all unique values of field2 will be listed
with this code:
[php]
<select>
<?
$sql = "Select $field FROM myTable GROUP BY $field";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
[/php]

i beileve that this is a small problem.. so how can i devided it to smallers :-) !!
Aug 15 '07 #19
pbmods
5,821 Expert 4TB
Heya, Coool.

Think about it this way.

JavaScript, just like HTML, is evaluated by the browser, not the server.

For example, if you wanted to output a div, you would use code similarly to this:
Expand|Select|Wrap|Line Numbers
  1. echo '<div>some text goes here</div>';
  2.  
Note that you're not actually outputting a DIV. Rather, you're outputting code that tells the browser, "Create a DIV and append a #text child with the value, 'some text goes here'".

Similarly, you can "interact" with javascript:
Expand|Select|Wrap|Line Numbers
  1. echo '
  2. <script type="text/javascript">
  3.      var myName = "', $_SESSION['name'], '";
  4. </script>';
  5.  
Note that you're not actually sending $_SESSION['name'] to the browser. When PHP evaluates this code, it will turn it into something like this:
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.      var myName = "coool";
  3. </script>
  4.  
Note that you're not actually creating the myName variable on the server. Again, you send HTML and JavaScript to the browser, and the *browser* interprets this code and creates the myName variable.

With this in mind, how do we 'transport' your MySQL results from the PHP side to JavaScript?

Fortunately, there's a PHP function that will make 90% of this a lot easier!

Let's start with an example:
Expand|Select|Wrap|Line Numbers
  1. $resultSet = array(
  2.     'USA'    => array(
  3.         'New York',
  4.         'Chicago',
  5.         'Dallas'
  6.     ),
  7.  
  8.     'Japan'    => array(
  9.         'Tokyo',
  10.         'Hiroshima'
  11.     )
  12. );
  13.  
  14. echo '<script type="text/javascript">
  15.     var theArray = eval("(" + "', json_encode($resultSet), '" + ")");
  16.     alert(theArray["USA"][2]);
  17. </script>';
  18.  
Here's what PHP actually sends to the browser:
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.     var theArray = eval("(" + "{'USA':['New York','Chicago','Dallas'],'Japan':['Tokyo','Hiroshima']}" + ")");
  3.     alert(theArray["USA"][2]);
  4. </script>
  5.  
You can probably tell that I am well-versed in the names of non-US cities :P
Aug 15 '07 #20
coool
67
I have understand what I tried to implement something in reality - felt reallyyyy sad as I couldn't :(

[php]
echo '<script type="text/javascript">
function secondList(field)
{
var theArray = eval("(" + "', json_encode($data), '" + ")");
var value;
content = theArray[field][];
newListHTML="<select>";
for(value in content)
{
newListHTML+="<option value=\""+content[value]+"\">"+content[value]+"</option>";
}
newListHTML+="</select>";
document.getElementById("newListDiv").innerHTML= newListHTML;
}

</script>';


[/php]

am I near :-s !!
Aug 15 '07 #21
pbmods
5,821 Expert 4TB
Heya, Coool.

You are very close :)

This line:
Expand|Select|Wrap|Line Numbers
  1. content =  theArray[field][];
  2.  
Is not valid syntax in any language. In PHP, you'd be saying, "create a new, empty element in the array and set content equal to it". In Javascript, you'd be saying, "parse error".

Did you mean this instead:
Expand|Select|Wrap|Line Numbers
  1. content =  theArray[field];
  2.  
Aug 15 '07 #22
coool
67
I don't seem that close :(

I've fixed it as you told me - it doesn't work ! well I meant to say an array with 2-dim

here's my code - can you see where's the error !
[php]
<?
$sql1 = "SHOW FIELDS FROM TableOne";
$res1 = mysql_query($sql1);
$data = array();
while($row1 = mysql_fetch_row($res1))
{
$sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
$res2 = mysql_query($sql2);
while($row2 = mysql_fetch_row($res2))
{
$data[$row1[0]][] = $row2[0];
}
}

echo '<script type="text/javascript">
function secondList(field)
{
var theArray = new Array();
theArray = eval("(" + "', json_encode($data), '" + ")");
var value;
var content = new Array();
content = theArray[field];
newListHTML="<select>";
for(value in content)
{
newListHTML+="<option value=\""+content[value]+"\">"+content[value]+"</option>";
}
newListHTML+="</select>";
document.getElementById("newListDiv").innerHTML= newListHTML;
}

</script>';
?>

<form action="" method='POST'>

<select name="firstList" onchange="secondList(this.value)">
<option value=''></option>
<?
$sql = "SHOW FIELDS FROM TableOne";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>

<div id='newListDiv'>
</div>

</form>
[/php]

when I load the page into a browswer -- at the bottom they said there's an error in this page - they meant the javascript thing :(

shall i use AJAX (scaryyy!) or it's too late -- how long will it take !!
Aug 16 '07 #23
pbmods
5,821 Expert 4TB
Heya, Coool.

I made a few changes. Most notably, I moved theArray outside of the function (since you only need to create it once per page load).

Also notice that the select element has a slightly different onchange.

Otherwise it looks pretty good. If you're still getting an error, post back with the error message, as well as the EVALUATED source of the page (i.e., View Source in your browser, copy-paste).

Expand|Select|Wrap|Line Numbers
  1. <?
  2. $sql1 = "SHOW FIELDS FROM TableOne";
  3. $res1 = mysql_query($sql1);
  4. $data = array();
  5. while($row1 = mysql_fetch_row($res1))
  6. {
  7.         $sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
  8.         $res2 = mysql_query($sql2);
  9.         while($row2 = mysql_fetch_row($res2))
  10.         {
  11.                 $data[$row1[0]][] = $row2[0];
  12.         }
  13. }
  14.  
  15.      echo '<script type="text/javascript">
  16.      var theArray = eval("(" + "', json_encode($data), '" + ")");
  17. function secondList(field)
  18. {
  19.         var value, content, newListHTML;
  20.         content = theArray[field];
  21.         newListHTML = "<select>";
  22.         for(value in content)
  23.         {
  24.             newListHTML += "<option value=\"" + content[value] + "\">" + content[value] + "</option>";
  25.         }
  26.         newListHTML += "</select>";
  27.         document.getElementById("newListDiv").innerHTML = newListHTML;
  28. }
  29.     </script>';
  30. ?>
  31.  
  32. <form action="" method='POST'>
  33.  
  34. <select name="firstList" onchange="secondList(this.options[this.selectedIndex].value)">
  35. <option value=''></option>
  36. <?
  37.              $sql = "SHOW FIELDS FROM TableOne";
  38.              $result = mysql_query($sql);
  39.  
  40.              while($row = mysql_fetch_row($result))
  41.              { ?>
  42.                    <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
  43.              <? }
  44. ?>
  45. </select>
  46.  
  47. <div id='newListDiv'>
  48. </div>
  49.  
  50. </form>
  51.  
Aug 16 '07 #24
coool
67
Alright ! the problem doesn't seem to be from the function

but the problem is when i'm "echo"ing the javascript !

but how can i use "data" then !!

example (not working):
[php]
echo '<script type="text/javascript">
function secondList(field)
{
var newListHTML;
newListHTML = "yesss";
document.getElementById("newListDiv").innerHTML = newListHTML;
}
</script>';

<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.options[this.selectedIndex].value);">
...........
.........
...........
</select>

<div id='newListDiv'>
</div>
</form>
[/php]

BUT ! when i do this --- code is workin -- i.e displaying "yessss" when something selected from the firstList !!
example (working):
[php]

<script language='javascript'>
function secondList(field)
{
var newListHTML;
newListHTML = "yesss";
document.getElementById("newListDiv").innerHTML = newListHTML;
}
</script>

<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.options[this.selectedIndex].value);">
...........
.........
...........
</select>

<div id='newListDiv'>
</div>
</form>
[/php]

is there any solution ! .. or shall we give up and try using AJAX :( :S
Aug 16 '07 #25
code green
1,726 Expert 1GB
I told you in my post to break this down into individual problems.
This was your reply
this is not many problems together - it's only one problem called (controlled/dependent 2 lists) where what's selected in one list should be used in mysql query in the second list to get the values of the first list selection
Which has proved to be wrong.
Aug 16 '07 #26
coool
67
okay then tell me "cold green" what's the sup problems of this problem ??

I really can't think of sub-problems for this problem.. :)
Aug 16 '07 #27
pbmods
5,821 Expert 4TB
Are we having fun yet?

What does your output look like?
Aug 16 '07 #28
coool
67
here's the source code - (from the browser)

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.      var theArray = eval("(" + "{"field1":["value1"],"field2":["value1","value2","value3","value4","value5"],"field3":["value1","value2","value3","value4","value5"],"field4":["value1","value2","value3"]}" + ")");
  3. function secondList(field)
  4. {
  5.         var value, content, newListHTML;
  6.         content = theArray[field];
  7.         newListHTML = "<select>";
  8.         for(value in content)
  9.         {
  10.             newListHTML += "<option value=\"" + content[value] + "\">" + content[value] + "</option>";
  11.         }
  12.         newListHTML += "</select>";
  13.         document.getElementById("newListDiv").innerHTML = newListHTML;
  14. }
  15. </script>
  16.  
  17. <form action="" method='POST'>
  18.     <select name="firstList" onchange="secondList(this.options[this.selectedIndex].value);">
  19.         <option value=''></option>
  20.                        <option value="field1">field1</option>
  21.                                 <option value="field2">field2</option>
  22.                                 <option value="field3">field3</option>
  23.                                 <option value="field4">field4</option>
  24.     </select>
  25.     <div id='newListDiv'></div>
  26. </form>
  27.  
yeah I'm having fun :) , but this will be more fun if we find the solution ;)
Aug 16 '07 #29
pbmods
5,821 Expert 4TB
Heya, Coool.

Change this line in your source:
Expand|Select|Wrap|Line Numbers
  1. var theArray = eval("(" + "', json_encode($data), '" + ")");
  2.  
To:
Expand|Select|Wrap|Line Numbers
  1. var theArray = eval("(" + \'', json_encode($data), '\' + ")");
  2.  
Aug 16 '07 #30
coool
67
same thing :(

nothing working..
Aug 16 '07 #31
coool
67
any clue, guys ?

I really need some help..
Aug 16 '07 #32
pbmods
5,821 Expert 4TB
Heya, Coool.

What error are you getting?
Aug 16 '07 #33
coool
67
no error is displayed !!

it's java.. they say there's an error - at the bottom-bar of the browser - but they dont' say what's wrong ! .. it just mean there's something wrong with javascript..

i've copied and pasted here / above / the source code from the browser ..

what do you think !! .. can you see where is the error !

maybe if you tried my code using one of a database table you have !! , you can find the error :) !
Aug 16 '07 #34
jx2
228 100+
any clue, guys ?

I really need some help..
hey im here ;-)
pbmods gave you answer - i try to explain it to you :-)

[php]
// whats wrong with that?
echo "very important guy said"i am god" thatwhat he said";

// you got error cos you closing quotation mark "very important guy said"
// and after that "computer" expect ';' or '.'
// so becose that is wrong we need to tell "computer"
// that this is not speach mark so we do \"
// backslash tells "computer" do not worry about next sign its not important
// for you its onty a part of string
//so

echo "very important guy said \"i am your god\" that what he said";

//got it? php will output "
[/php]
other special characters are \n \t \r \' \"

i know its a bit fuzzy explenation but i did my best :-]

regardz
jx2
Aug 16 '07 #35
jx2
228 100+
no error is displayed !!

it's java.. they say there's an error - at the bottom-bar of the browser - but they dont' say what's wrong ! .. it just mean there's something wrong with javascript..
they also said the line number of the error and character
if that java script just check sorce of the page to see if you did good job in php

my guess is \"
Aug 16 '07 #36
coool
67
hey jx2 -- long time no seen !

hmmm,

so u're saying there's something wrong with this:
[php]
echo '<script type="text/javascript">
var theArray = eval("(" + \'', json_encode($data), '\' + ")");
</script>';
[/php]

hmmmmmmmmmm.......
shouldn't it be like this:
[php]
echo '<script type="text/javascript">
var theArray = eval(\"(\" + \' ', json_encode($data), ' \' + \")\");
</script>';
[/php]

here's the error I'm getting when I load the page (browser
--- only this .. trust meee :-)

Aug 16 '07 #37
jx2
228 100+
trust me it says which line it is ;-) lol
just click on this yellow triangle
Aug 17 '07 #38
jx2
228 100+
[php]echo '<script type="text/javascript">
var theArray = eval("(" + \'', json_encode($data), '\' + ")");
</script>';[/php]
well you need to know which one you want to "print" ( to be marked \ )

this above look like a mess to me :-)
Aug 17 '07 #39
coool
67
lol, calm down... be cooooool :P

I'll try now.. brb in few minutes :D
Aug 17 '07 #40
coool
67
ahaaaaaaaaaaaa

they're saying

in this line:
[php]
<script>
var theArray = eval("("+',json_encode($data),'+")");
</script>
[/php]

that the error is .... missing ']' at character 1

strange error !!
Aug 17 '07 #41
coool
67
HEY HEY

I HAVE FIXED IT

can't beilve ittttt .. .

wooooow

finaaaallyyyyy

okay here's what made things workinggggg :DDDD

[php]
<script>
var theArray = eval(',json_encode($data),');
<script>
[/php]

THANKS very much for your helppp PBmods and jx2 : ) : ) : ) : )
Aug 17 '07 #42
jx2
228 100+
<script>
var theArray = eval("("+',json_encode($data),'+")");
</script>
LOL
lol lol
and you dont know whats wrong with that? lol
hehe

i'm not sure youreally need eval() function here ... it would just print
Array("var1","var2".... ,"varX"); insted - but that different story

json_encode() is... rather php function not a javascript a specialy that you using $data :-)

you need to ask yourself question - what did i want to print in this place
(i know it should be array) read about it here

and now simply answers :-) lol
1. you didnt print what is needed - you need to use \ so you get in this place something what look like

var theArray = eval("(" + DATA TEXT HERE + ")");

2. coma is not a dot look here

"this is string".aPHPfunction()."string".$phpVariable;
in other world dot is a plus sign for to use with strings

i hope this is not clear ... learn ... read... and ask...

regards jx2
Aug 17 '07 #43
pbmods
5,821 Expert 4TB
...


Ohhhh right!

:P

I feel kinda silly now.

See, using the eval() function is only necessary when returning from an AJAX call! You can actually just insert your json_encode()'ed data directly into your JavaScript, since it outputs valid JavaScript.

*sigh* It's been a long week.

At any rate, glad to hear you got it working! Good luck with your project, and if you ever need anything, post back anytime :)
Aug 17 '07 #44
coool
67
You guys are wonderful - I wish I know 1000000 people like both of you :-)

now.. I've a little question !

with this technique we used in this post... and with the AJAX technique...

is it always.......... take long in loading the page ??

as we are loading all the array in the source code (when u see in the browser) !!

or ... do you say that AJAX is faster !!
Aug 17 '07 #45
jx2
228 100+
You guys are wonderful - I wish I know 1000000 people like both of you :-)

now.. I've a little question !

with this technique we used in this post... and with the AJAX technique...

is it always.......... take long in loading the page ??

as we are loading all the array in the source code (when u see in the browser) !!

or ... do you say that AJAX is faster !!
all depends
if you got many options (as you have) probably ajax is faster
but if you got just a few categories i wouldnt boder with ajax (you would have to wait for response frome server when you choose something

how big is your page after loading?

pbmods - are we using ajax here? its so long post that i ve got lost :-)
Aug 17 '07 #46
pbmods
5,821 Expert 4TB
Heya, Coool.

Since you seem enthralled with the idea of integrating AJAX into your script, here's how your page would work if you integrated AJAX functionality:
  • When the User selects an option from the first select element, the browser calls a JavaScript function that creates a new AJAX object (also [properly] known as an XmlHttpRequest object).
  • The AJAX function sends a request to the server for a separate page (this is key) that takes in a parameter and returns ONLY the JavaScript needed to populate the second select.

    For example, the AJAX call might send a request for http://your-site.tld/selector.php?cat=US and get back something like '["New York","Chicago","Dallas"]', which can be eval()'ed into a JavaScript Array.
  • From there, you do pretty much the same thing that you're doing now.

The benefits of using AJAX here:
  • You're loading the extra data *after* the page is finished loading, which speeds up the entire page load slightly.
  • The total load on your server is reduced slightly, as you don't have to send as much data.
  • If your database gets REALLY big, these savings will start becoming much more significant (on the order of seconds instead of nanoseconds).
  • You can cache results on the User's computer in a cookie to speed up execution time even more.

A couple of cons of using AJAX:
  • Unless you use intelligent prefetching methods, there will be a delay between when the User selects the option and when the second select becomes available.
  • Prefetching means that you may actually end up loading even *more* data than you really need because you don't know what the User will do next.

Still, AJAX is a fun way to make impressive applications. To get started, hop on over to this article, and be sure to post your questions in our JavaScript forum if you ever get stuck!

Good luck with your project, and if you ever need anything, post back anytime :)
Aug 17 '07 #47
coool
67
Good explainations, thanks


I'll go to the javascript forum......... as this post is reallyyyy long !!


see you there guys :-)
Aug 17 '07 #48
coool
67
how big is your page after loading?
really really big ------ like more than 50 000 distinct rows -- and it's increasing in a daily basis !! :-S
Aug 17 '07 #49

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Tony Grider | last post by:
I am trying to find a way to create dependent dropdown lists in C# The old way I knew involved javascript and will no longer work in the new design. I need for each list to be database driven (data...
6
by: Phil Howard | last post by:
I'm actually getting the mailing list mail, so I don't know what the deal is. Successful deliveries are coming from 64.117.225.209. But 207.173.200.206 has big problems. Sendmail is misconfigured...
8
by: Galina | last post by:
Hello I have 6 dependent list boxes on my ASP page:  Faculty;  Lecturer;  Course;  Course occurrence;  Group;  Week commencing date. When faculty is selected, lists of lecturers and...
10
by: Mark | last post by:
Hi, I have two select boxes, like country and province. When a user select a country the list of provinces should change. How might one go about doing this?
5
by: rodeoval | last post by:
I need to have three drop down lists, but the dependent should get the values from the database without refreshing the page..If knows,someone pls reply soon
1
by: jdkhan | last post by:
i want to use two lists one dependent on other just like city dependent on country selection how can i do this in single page using PHP
1
by: avigiano | last post by:
Good morning. I have a contacts database that tracks the regular things like phone numbers, address etc. User searches for contacts through a combo box that lists entires by last name. I've...
5
by: Bels | last post by:
I am currently designing a real estate website using Dreamweaver CS3, php, MySQL on a Mac. On it is a 'property search' form that queries the property database. The form consists of 5 dropdown lists....
26
by: jmartmem | last post by:
Greetings, I have an ASP page with two dynamic dependent list boxes written in JavaScript. My dependent lists work great, but my problem is that the values for "Program_Name" and "Project_Name"...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.