0

how can i do this. if i select in first dropdown hand spa, hand massage should only appear in the second dropdown.

i want the values in my second dropdown will depend on the first here is my current code:

<body>
<form method='index.php' action='post'>

    Category:  <select id="id" name="category">
    <?php
        $qry=mysql_query("SELECT * FROM categ",$con);
        while($rs = mysql_fetch_object($qry)){
            echo "<option id='".$rs->categid."'>" .$rs->categname."</option>";
        }
    ?>
    </select>
<br>
    sub categ:  <select id="id" name="subcategory">
    <?php
        $qry=mysql_query("SELECT * FROM serv",$con);
        while($rs = mysql_fetch_object($qry)){
            echo "<option id='".$rs->servid."'>" .$rs->servname."</option>";
        }
    ?>
    </select>

</form>
</body>

here is my database

CREATE TABLE IF NOT EXISTS `categ` (
  `categid` int(11) NOT NULL AUTO_INCREMENT,
  `categname` varchar(255) NOT NULL,
  PRIMARY KEY (`categid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `categ`
--

INSERT INTO `categ` (`categid`, `categname`) VALUES
(1, 'hand spa'),
(2, 'foot spa');


CREATE TABLE IF NOT EXISTS `serv` (
  `servid` int(11) NOT NULL AUTO_INCREMENT,
  `servname` varchar(255) NOT NULL,
  `categid` int(11) NOT NULL,
  PRIMARY KEY (`servid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `serv`
--

INSERT INTO `serv` (`servid`, `servname`, `categid`) VALUES
(1, 'haaaanndddd massage', 1),
(2, 'footssppaa', 2);
  • I think this can be easily done using AJAX. Have you tried that ? – Maximus2012 Sep 27 '13 at 19:12
  • not still sir. i have no knowledge of it sir. but ill make a research – user2805941 Sep 27 '13 at 19:14
  • see if this helps: http://stackoverflow.com/questions/15356291/how-can-i-get-countries-states-list-from-states-table-when-i-select-country-fro?rq=1 – Maximus2012 Sep 27 '13 at 19:15
  • thanks guys. i will try all of this – user2805941 Sep 27 '13 at 19:23
  • this your question is simple logic, you needs to creat some function which detect the select action so when select first select then for the select you will want to have somthing like this: servid."'>" .$rs->servname.""; } ?> – ShapCyber Sep 27 '13 at 19:23
  • This may be of some use too: http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/ – Moob Sep 27 '13 at 19:24
  • another thing is that where is your 'value' attribute in the select option you only have 'id' attr – ShapCyber Sep 27 '13 at 19:30
  • Please see [my answer below](http://stackoverflow.com/questions/19058304/dropdown-options-is-dependent-from-another-dropdown-options-all-value-from-data/19059804#19059804). I was unable to customize it for your specific Spa project because that would take too long. (On the other hand, now you will learn a little more by customizing it yourself.) – cssyphus Sep 27 '13 at 20:48

2 Answers2

1

Here is an example that you can customize to do what you want. Essentially, you can use jQuery / AJAX to accomplish this.

The example below creates a second drop-down box, populated with the values found. If you follow the logic line by line, you will see it is actually quite simple. I left in several commented-out lines that, if uncommented (one at a time) will show you what the script is doing at each stage.

FILE 1 -- TESTER.PHP

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
//alert('Document is ready');

                $('#stSelect').change(function() {
                    var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);

                    $.ajax({
                        type: "POST",
                        url: "another_php_file.php",
                        data: 'theOption=' + sel_stud,
                        success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
                            $('#LaDIV').html(whatigot);
                            $('#theButton').click(function() {
                                alert('You clicked the button');
                            });
                        } //END success fn
                    }); //END $.ajax
                }); //END dropdown change event
            }); //END document.ready
        </script>
    </head>
<body>

    <select name="students" id="stSelect">
        <option value="">Please Select</option>
        <option value="John">John Doe</option>
        <option value="Mike">Mike Williams</option>
        <option value="Chris">Chris Edwards</option>
    </select>
    <div id="LaDIV"></div>

</body>
</html>

FILE 2 - another_php_file.php

<?php

//Login to database (usually this is stored in a separate php file and included in each file where required)
    $server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
    $login = 'root';
    $pword = '';
    $dbname = 'test';
    mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
    mysql_select_db($dbname) or die($connect_error);

//Get value posted in by ajax
    $selStudent = $_POST['theOption'];
    //die('You sent: ' . $selStudent);

//Run DB query
    $query = "SELECT * FROM `category` WHERE `master` = 0";
    $result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
    $num_rows_returned = mysql_num_rows($result);
    //die('Query returned ' . $num_rows_returned . ' rows.');

//Prepare response html markup
    $r = '  
            <h1>Found in Database:</h1>
            <select>
    ';

//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
    if ($num_rows_returned > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
        }
    } else {
        $r = '<p>No student by that name on staff</p>';
    }

//Add this extra button for fun
    $r = $r . '</select><button id="theButton">Click Me</button>';

//The response echoed below will be inserted into the 
    echo $r;

To answer the usual question: "How do you make the 2nd drop down box populate fields that are only relevant to a selected option from the 1st drop down box?"

A. Inside the .change event for the first dropdown, you read the value of the first dropdown box:

$('#dropdown_id').change(function() {
var dd1 = $('#dropdown_id').val();
}

B. In your AJAX code for the above .change() event, you include that variable in the data you are sending to the 2nd .PHP file (in our case, "another_php_file.php")

C. You use that passed-in variable in your mysql query, thereby limiting your results. These results are then passed back to the AJAX function and you can access them in the success: portion of the AJAX function

D. In that success function, you inject code into the DOM with the revised SELECT values.


This is how the above example works:

  1. The user chooses a student name, which fires the jQuery .change() selector

  2. Here is the line where it grabs the option selected by the user:

    var sel_stud = $(this).val();

  3. This value is sent to another_php_file.php, via this line of the AJAX code:

    data: 'theOption=' + sel_stud,

  4. The receiving file another_php_file.php receives the user's selection here:

    $selStudent = $_POST['theOption'];

  5. Var $selStudent (the user's selection posted in via AJAX) is used in the mysql search:

    $query = " SELECT * FROM `category` WHERE `master` = 0 AND `name` = '$selStudent' ";

    (When changing the example to suit your database, the reference to $selStudent was removed. But this (here, above) is how you would use it).

  6. We now build a new <SELECT> code block, storing the HTML in a variable called $r. When the HTML is fully built, I return the customized code back to the AJAX routine simply by echoing it back:

    echo $r;

  7. The received data (the customized <SELECT> code block) is available to us inside the AJAX success: function() {//code block}, and I can inject it into the DOM here:

    $('#LaDIV').html(whatigot);

And voila, you now see a second dropdown control customized with values specific to the choice from the first dropdown control.

Works like a non-Microsoft browser.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

If i got your question clearly, you can study this code and customize it to suit your needs. its simple and straight forward:

Let say our purpose is to manage movies

<label>Movie Category</label>
    <select name="movieCategory" id="movieCategory">
                <option value="">--- S e l e c t ---</option>
               <?php
    $movieCategory= array("Action","Romance","Horror","Comedy","Music","Interviews");

    reset($movieCategory);
    while (list($key ,  $value) = each($movieCategory)) {

         echo " <option id='".$value."' value='".$value."'>".$value."</option>";
    }
    ?>           
              </select>
              <br>
          <label>Movie SubCategory</label>
              <select name="subCategory" id="subCategory">
                <option value="">--- S e l e c t ---</option>
               <?php
    $subCategory= array("Action","Romance","Horror","Comedy","Music","Interviews");

    reset($subCategory);
    while (list($key ,  $subvalue) = each($subCategory)) {

         echo " <option id='".$subvalue."' value='".$subvalue."'>".$subvalue."</option>";
    }


    ?>

              </select>

    <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>

    <script language="javascript" type="text/javascript">
    $(function () {

    $('select#movieCategory').change(function(){

    $('select#subCategory  option#'+$(this).val()).attr( "selected" , "selected"  )
    });


    });

</script>
ShapCyber
  • 3,382
  • 2
  • 21
  • 27