473,499 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use an html list box to populate another list box

maxamis4
295 Recognized Expert Contributor
Hello,

I am currently building a php website. My input form has a list box which I have populated using mysql. What i want to do is populate another list box using the first list box.

Both boxes will be pulling from a my sql database but one will use the first box as a filter. After doing some research in google I found that ajax would be the best way to do this. I however can not find a very simple step by step on how to do this.

I do understand that PHP is server side and i do understand that I need to reload the page. My problem is how do I force a reload on selection (obviously ajax is the way) and how to do it. Does anyone have any examples on how to do this?
Jun 28 '10 #1
5 4713
Dormilich
8,658 Recognized Expert Moderator Expert
if you want to use AJAX, then you don’t need a reload (the one excludes the other).

if you’re using reloads, it is just a matter of passing around the value of the first select to the builder of the second.

(common search term: combo box)

copied from my page (reload based, should give you an impression):
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     $opt2 = $opt3 = "";
  3.     try
  4.     {
  5.         if (isset($_POST['play']))
  6.         {
  7.             $opt2 = new Option(getAkte((int) $_POST['play']), "akt");
  8.             $opt2->indentation = 6;
  9.         }
  10.         if (isset($_POST['akt']))
  11.         {
  12.             $opt3 = new Option(getSzenen((int) $_POST['akt']), "szene");
  13.             $opt3->indentation = 6;
  14.         }
  15.     }
  16.     catch (Exception $e)
  17.     {
  18.         echo '<p class="errmsg mitte">Keine Daten vorhanden.</p>';
  19.     }
  20. ?>
  21.             <fieldset>
  22.                 <legend>Szene</legend>
  23.                 <div class="tbl">
  24.                     <label for="akt">Akt</label>
  25.                     <br/>
  26.                     <select name="akt" id="act" size="5" style="width: 6em;">
  27. <?php echo $opt2; ?>
  28.                     </select>
  29.                 </div>
  30.                 <div class="tbl">
  31.                     <label for="scene">Szene</label>
  32.                     <br/>
  33.                     <select name="szene" id="scene" size="5" style="width: 6em;">
  34. <?php echo $opt3; ?>
  35.                     </select>
  36.                 </div>
  37.             </fieldset>
  38.  
Jun 28 '10 #2
maxamis4
295 Recognized Expert Contributor
Want to give my thanks to web3schools for the example code http://www.w3schools.com/php/php_ajax_database.asp


Dormilich tried to make sense on what you put up and then look around again. Seems like the option everyone recommended was ajax. This is what I have so far:

In the head of my code I have the following

The current page being view is blank_risk_form.php. i would like to stay on one page if possible

Expand|Select|Wrap|Line Numbers
  1. <SCRIPT language="javascript" type='text/javascript'>
  2.  
  3.  
  4. //==================================COMBO AUTO GENERATE=====================================
  5.     function showUser(str)
  6.     {
  7.         if (str=="")
  8.           {
  9.  
  10.             document.getElementById("txtHint").innerHTML="";
  11.               return;
  12.           } 
  13.         if (window.XMLHttpRequest)
  14.           {// code for IE7+, Firefox, Chrome, Opera, Safari
  15.               xmlhttp=new XMLHttpRequest();
  16.          }
  17.         else
  18.           {// code for IE6, IE5
  19.               xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  20.          }
  21.         xmlhttp.onreadystatechange=function()
  22.           {
  23.               if (xmlhttp.readyState==4 && xmlhttp.status==200)
  24.             {
  25.                 document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  26.                }
  27.          }
  28.         xmlhttp.open("GET","blank_risk_form.php?dep_code="+str,true);
  29.         xmlhttp.send();
  30.     }
  31.  
  32. </SCRIPT>    
  33.  
  34.  

in the main body I have the following:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     //Include database connection details
  3.     require_once('configrisks.php');
  4.  
  5.     //Array to store validation errors
  6.     $errmsg_arr = array();
  7.  
  8.     //Validation error flag
  9.     $errflag = false;
  10.  
  11.     //Connect to mysql server
  12.     $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
  13.     if(!$link) {
  14.         die('Failed to connect to server: ' . mysql_error());
  15.     }
  16.  
  17.     //Select database
  18.     $db = mysql_select_db(DB_DATABASE);
  19.     if(!$db) {
  20.         die("Unable to select database");
  21.     }
  22.  
  23.     //Function to sanitize values received from the form. Prevents SQL injection
  24.     function clean($str) {
  25.         $str = @trim($str);
  26.         if(get_magic_quotes_gpc()) {
  27.             $str = stripslashes($str);
  28.         }
  29.         return mysql_real_escape_string($str);
  30.     }
  31.  
  32.  
  33.     //************************************************************************************
  34.     //                                        BUILD ARRAYS
  35.     //====================================================================================
  36.  
  37.  
  38. //================================ARRAY 3===================================
  39.         //CREATE DROP DOWNS FOR FORM USAGE
  40.     $sql = "SELECT code, des FROM tbl_department WHERE proj_code = 'risk' AND active = 1";
  41.     $dep = mysql_query($sql);
  42.     if($dep) 
  43.     {
  44.         $dep_num = mysql_num_rows($dep);
  45.  
  46.  
  47.         //Loop through data array
  48.         while($row=mysql_fetch_assoc($dep))
  49.         {
  50.             $dep_array_code[]=$row["code"];
  51.             $dep_array_des[]=$row["des"];
  52.         };
  53.  
  54.     }
  55.     else
  56.     {
  57.  
  58.         echo "Array3";
  59.         die('Error reading user data');
  60.     }
  61.  
  62.     //================================ARRAY 4===================================
  63.     //CREATE DROP DOWNS FOR FORM USAGE
  64.  
  65.     $dep_code=$_GET['dep_code'];
  66.     echo 'This is my department code'.$dep_code;
  67.     echo '<br>';
  68.  
  69.     if(isset($dep_code))
  70.     {
  71.         $sql="SELECT id, realname, firstname FROM tbl_users WHERE ((active = 1) AND (st_manager=1 OR rsk_manager =1)) AND dep_code = '$dep_code' ORDER BY realname";
  72.     }
  73.     else
  74.     {
  75.         $sql="SELECT * FROM tbl_users WHERE id = -1"; 
  76.     }
  77.  
  78.     $user = mysql_query($sql);
  79.     if($dep) 
  80.     {
  81.         $user_num = mysql_num_rows($user);
  82.  
  83.  
  84.         //Loop through data array
  85.         while($row=mysql_fetch_assoc($user))
  86.         {
  87.             $user_array_id[]=$row["id"];
  88.             $user_array_last[]=$row["realname"];
  89.             $user_array_first[]=$row["firstname"];
  90.  
  91.         };
  92.  
  93.     }
  94.     else
  95.     {
  96.  
  97.         echo "Array4";
  98.         die('Error reading user data');
  99.     }
  100.  
  101. ?>    
  102.  
I set the value to negative one in order to keep the drop down empty. Don't know if thats even necessary but it just seemed right.

For the html part I did the following
Expand|Select|Wrap|Line Numbers
  1. <FORM NAME="blank_risk_form" id="blank_risk_form" method="post" action="submitnewrisk.php" onsubmit="return validate_form(this)">
  2.  
  3.  
Please note that the form is used for the rest of the page with other variables. I am showing this form in the case that someone says that I need a form.


This is the first drop down that returns the value that query's the second drop down and calls the javascript function. Here is where I don't see it working and where I need help

Expand|Select|Wrap|Line Numbers
  1. <th scope="col"><select name="cbo_subtsk" id="select" onchange="showUser(this.value)">
  2.               <?php
  3.                     //BUILD DROP DOWN LIST
  4.  
  5.                     //FOR STATEMENT 1 START
  6.                         echo '<option value=""></option>';
  7.                         for ($array_1index=0; $array_1index < $dep_num; $array_1index += 1) 
  8.                         {
  9.  
  10.                                 echo '<option value='; 
  11.                                 echo $dep_array_code[$array_1index];
  12.                                 echo '>'; 
  13.                                 echo $dep_array_des[$array_1index]; 
  14.                                 echo '</option>';
  15.  
  16.                         }//FOR STATEMENT 1 END
  17.  
  18.                     ?>
  19.             </select></th>
  20.  
  21.  
The second drop down should populate in theory based on the one above which is where I am having problems

Expand|Select|Wrap|Line Numbers
  1.  
  2.  <th scope="col"><span class="style4">
  3.               <select name="cbo_owner" id="select9" >
  4.                 <?php
  5.                     //BUILD DROP DOWN LIST
  6.  
  7.                     //FOR STATEMENT 1 START
  8.                     echo '<option value=""></option>';
  9.                         for ($array_1index=0; $array_1index < $user_num; $array_1index += 1) 
  10.                         {
  11.  
  12.                                 echo '<option value='; 
  13.                                 echo $user_array_id[$array_1index];
  14.                                 echo '>'; 
  15.                                 echo $user_array_last[$array_1index];
  16.                                 echo ", ";
  17.                                 echo $user_array_first[$array_1index];
  18.                                 echo '</option>';
  19.  
  20.                         }//FOR STATEMENT 1 END
  21.  
  22.                     ?>
  23.               </select>
  24.             </span></th>
  25.  
  26.  
At this point the only thing I can say is that I am not sure why its not working. Any assistance on how to trouble shoot it would be greatly appreciated it
Jun 29 '10 #3
Dormilich
8,658 Recognized Expert Moderator Expert
i would like to stay on one page if possible
this approach doesn’t work with AJAX. you need to call another page.

doing the AJAX way, you query a script, which returns you the data you need for the second <select>. this may either be pure data (building the <option> elements in JS) or a ready made chunk of HTML to directly inject in the document.
Jun 29 '10 #4
maxamis4
295 Recognized Expert Contributor
@Dormilich
Based on what you have mentioned it seems that reload is the only way in order to stay on the same page. Do you happen to have a couple links that I could use to create this? I know your example outlines the post method but I am still a little blurry on how I can use the "on change" action to re-query the page. The other part I am worried about is the javascript validation that I have on the page. Would the reload trigger the validation part?

I get the concept that the validation is only triggered on submit based on the form so my guess is that it would not, but I would rather ask the question than lead anyone else to another question.
Jun 30 '10 #5
Dormilich
8,658 Recognized Expert Moderator Expert
Based on what you have mentioned it seems that reload is the only way in order to stay on the same page.
no. you’re misunderstanding AJAX. AJAX is just a function that does a server request. because you do not do any page reloads, you stay at the same page. and because of that you can’t use the same page as AJAX’s URL target.
Jun 30 '10 #6

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

Similar topics

4
3824
by: Henk | last post by:
Hi, I am new to the c-programming language and at the moment I am struggling with the following: I want to read a file using fread() and then put it in to memory. I want to use a (singel)...
1
10255
by: mmohlameane | last post by:
Hi! I would like to populate the dropdown with the list of all country name ( e.g South Africa, Zimbabwe,United States, etc). Is there a function to do that? Thanks --- Posted using...
15
4712
by: Nathan | last post by:
I have an aspx page with a data grid, some textboxes, and an update button. This page also has one html input element with type=file (not inside the data grid and runat=server). The update...
7
2439
by: David | last post by:
Hello All, I am trying to split a long list of list items ( li ) into 3 groups and append them to a div on the page. Below is the test page that I have created. It's fairly simple but I can't...
1
1936
by: subhashk | last post by:
Is it possible to create a editable HTML drop down list using javascript?
2
4830
by: jej1216 | last post by:
Using PHP to populate a form, I am not able to display any text area data -- it displays as blank. <?php echo "<textarea rows=11 cols=120 name=inc_descr value='".$incdescr."'></textarea>"; ?> ...
3
2897
by: =?Utf-8?B?RGF2ZSBU?= | last post by:
Is there a way to add columns to the drop down list and list box controls so I can show multiple columns? My DBA refuses to allow concatenation in SQL
0
922
by: caroliina | last post by:
i made a list of lists but i cant write it into a file. how do i get the first string in a sublist? -- View this message in context:...
3
2405
by: Riccardo Murri | last post by:
Hello, I have some code that stops when trying to find a graph in a list of similar graphs:: (Pydb) list 110 try: 111 canonical = self.base 112 except ValueError: 113 ...
1
3445
by: ganesandeiav | last post by:
Dear frnds I am using jsp.I have a problem file upload using html control.I want filter seleted file such as *.gif&*.jpeg images .It should be list out jpeg gif image only. iam try this code but...
0
7007
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
7220
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7388
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...
0
5470
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4600
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3099
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1427
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
297
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.