0

I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:

<html>      
<head>
    <title>Dynamic Drop Down List</title>
</head>
<body>
    <form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
        department: 
        <select id="department" name="department" onchange="run()">  <!--Call run() function-->
            <option value="biology">biology</option>
            <option value="chemestry">chemestry</option>
            <option value="physic">physic</option>
            <option value="math">math</option>     
        </select><br><br>
        type_hire: 
        <select id="type_hire" name="type_hire" onchange="run()">  <!--Call run() function-->
            <option value="internal">Intenal</option>
            <option value="external">External</option>                
        </select><br><br>
        list of employees:
        <select name='employees'>
            <option value="">--- Select ---</option>
            <?php
            mysql_connect("localhost","root","");
            mysql_select_db("employees_hired");
            $list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
            while($row_list=mysql_fetch_assoc($list)){
            ?>
            <option value="<?php echo $row_list['name']; ?>">
                <?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
            </option>
            <?php
            }
            ?>
        </select>
    </form> 
</body>
</html>

The question I have is: how to get the selected values ​​from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values ​​from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?

6
  • Captain jQuery will save you here! Learn it and get a handle on AJAX requests. They will make this a breeze! jquery.com Commented Sep 19, 2013 at 1:04
  • It will make it easier and better you use ajax and jquery , you don't have to make inline php Commented Sep 19, 2013 at 1:05
  • @CP510 I guess you're right, but I have not enough experience or knowledge to understand JQuery or JS. im newbie in this world dude. Commented Sep 19, 2013 at 1:07
  • Working on the answer for you now. Commented Sep 19, 2013 at 1:10
  • @CP510 I found this example on the internet but now I created more questions than answers, when querying the database? Commented Sep 19, 2013 at 1:17

2 Answers 2

4

So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:

  1. Post the form to itself (as you have chosen) or
  2. use ajax (possibly via jQuery for quickness).

(both of these examples don't address how you are accessing the database)

1)

Using your run function:

<script type="text/javascript">
     function run(){
          document.getElementById('form1').submit()
     }
</script>

Additional PHP:

<?php
    if (isset($_POST['department']) && isset($_POST['type_hire']))
    {
        $value_of_department_list = $_POST['department'];
        $value_of_type_hire = $_POST['type_hire'];

        mysql_connect("localhost","root","");
        mysql_select_db("employees_hired");
        mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");

        while($row_list=mysql_fetch_assoc($list))
        {
            echo  "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
        }
    }
    else
    {
        echo  "<option>Please choose a department and a type of hire</option>";
    }
?>

2)

<script type="text/javascript">
     function run(){
          $.post('get_employees.php',$('form1').serialize(),function(data){

               var html = '';

               $.each(data.employees,function(k,emp){
                   $('select[name="employees"]').append($('<option>', {
                        value: emp.name,
                        text: emp.name
                    }));
               .html(html);
          },"json");
     }
</script>

And get_employees.php would contain something like:

<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
    $value_of_department_list = $_POST['department'];
    $value_of_type_hire = $_POST['type_hire'];
    $return = array();

    mysql_connect("localhost","root","");
    mysql_select_db("employees_hired");
    mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");

    while($row_list=mysql_fetch_assoc($list))
    {
        $return[]['name'] = $row_list['name'];
    }

    echo json_encode($return);
}
?>

Note, these are just quickly written examples. A lot more could/should be done here.

Sign up to request clarification or add additional context in comments.

Comments

2

Heres a modified jQuery version of your code. (With some cleanup)

<html>      
<head>
     <title>Dynamic Drop Down List</title>
</head>
<body>
    <form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
        department: 
        <select id="department" name="department" onchange="run()">  
            <!--Call run() function-->
            <option value="biology">biology</option>
            <option value="chemestry">chemestry</option>
            <option value="physic">physic</option>
            <option value="math">math</option>     
        </select><br><br>
        type_hire: 
        <select id="type_hire" name="type_hire" onchange="run()">  
            <!--Call run() function-->
            <option value="internal">Intenal</option>
            <option value="external">External</option>               
        </select><br><br>
        list of employees:
        <select name='employees'>
            <option value="">--- Select ---</option>
            <?php
            mysql_connect("localhost","root","");
            mysql_select_db("employees_hired");
            $list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
            while($row_list=mysql_fetch_assoc($list)){
            ?>
            <option value="<?php echo $row_list['name']; ?>">
                <? if($row_list['name']==$select){ echo $row_list['name']; } ?>
            </option>
            <?php
            }
            ?>
        </select>
    </form> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>

Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.php for more info on that. On to the scripting...

<script type="text/javascript">
$('#type_hire').change(function() {
   var selected = $('#type_hire option:selected');  //This should be the selected object
   $.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
      //Now data is the results from the DropdownRetrievalScript.php
      $('select[name="employees"]').html(data);
   }
}
</script>

Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.

Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.

2 Comments

I still dont understand what is DropdownRetrievalScript.php
It would be a seperate php file that would querry your database using the option the user selected. I just called it that randomly. But that script will be fed a $_GET['option'] variable to check which option was selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.