0

Hi

I managed to get the tutorial from the below link to work.
http://www.blueicestudios.com/chained-select-boxes-using-php-mysql-ajax/comment-page-11/#comment-34199

I would love to know how to edit this script so as to get the first dropdown to populate an already existing dropdown without the loader image and without the hiding of any dropdowns.

I would assume you only have to make changes to this section:

$(document).ready(function() {
    $('#wait_1').hide();
    $('#drop_1').change(function(){
      $('#wait_1').show();
      $('#result_1').hide();
      $.get("func.php", {
        func: "drop_1",
        drop_var: $('#drop_1').val()
      }, function(response){
        $('#result_1').fadeOut();
        setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
      });
        return false;
    });
});

function finishAjax(id, response) {
  $('#wait_1').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}

Your assistance is greatly appreciated

Edited by fabzster

3
Contributors
10
Replies
12
Views
4 Years
Discussion Span
Last Post by AleMonteiro
0

I just commented the code so you know what each line does:

$(document).ready(function() { // On DOM Loaded
    $('#wait_1').hide(); // Hides Wait_1
    $('#drop_1').change(function(){ // Listener for changes on Drop_1
      $('#wait_1').show(); // Shows Wait_1
      $('#result_1').hide(); // Hides Result_1
      $.get("func.php", { // Call func.php page in background
        func: "drop_1",
        drop_var: $('#drop_1').val()
      }, function(response){ // func.php response handler
        $('#result_1').fadeOut(); // Hides Result_1
        setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); // Calls finishAjax after 400ms
      });
        return false;
    });
});

function finishAjax(id, response) {
  $('#wait_1').hide(); // Hides Wait_1
  $('#'+id).html(unescape(response)); // Set the html of the result
  $('#'+id).fadeIn(); // Shows the result
}
0

I'm sorry, but I would love to see a better comment that just that. The reason is the function name explains itself, but what does it mean... I would like to see comment somewhat similar to below. Do not be too shy about commenting script/code. It will save your behind in the future when either you or others need a quick glance at it to understand what's going on. It could also serve as reasons why it is scripted/coded the way it is.

// When the page is loaded (document is ready), this function will be called.
$(document).ready(function() {
  $('#wait_1').hide();  // hide element named #wait_1 from the display
  $('#drop_1').change(function() { // assigned a customized function of onchange event to an element named #drop_1
     $('#wait_1').show();
     ...
     ...

Edited by Taywin

0

Hi

Many thanks for the time taken to reply, it is much appreciated.

This was taken from the tutorial link posted above and my Java script skills are somewhat non-existant. Hence why I did not comment anything above as I did not exactly know what it did. By looking at it I kinda understood what each section did, but am unable to change this (make it simpler) in order for it to do what I need.

This actually creates the <Select></select> box and has a little transistion before it does that.

I would really just like it to populate a <select> box that I already have on that page.

Could you perhaps assist with that?

The php file that is gets info from has 2 functions, the first one for retrieving the initial values:

function getTierOne()
{
    $result = mysql_query("SELECT DISTINCT tier_one FROM two_drops") 
    or die(mysql_error());

      while($tier = mysql_fetch_array( $result )) 

        {
           echo '<option value="'.$tier['tier_one'].'">'.$tier['tier_one'].'</option>';
        }

}

The second function to create the <Select>:

if($_GET['func'] == "drop_1" && isset($_GET['func'])) { 
   drop_1($_GET['drop_var']); 
}

function drop_1($drop_var)
{  
    include_once('db.php');
    $result = mysql_query("SELECT * FROM two_drops WHERE tier_one='$drop_var'") 
    or die(mysql_error());

    echo '<select name="tier_two" id="tier_two">
          <option value=" " disabled="disabled" selected="selected">Choose one</option>';

           while($drop_2 = mysql_fetch_array( $result )) 
            {
              echo '<option value="'.$drop_2['tier_two'].'">'.$drop_2['tier_two'].'</option>';
            }

    echo '</select> ';
    echo '<input type="submit" name="submit" value="Submit" />';
}

I would Like to have the second Select more like the first, like this:

function drop_1($drop_var)
{
    $result = mysql_query("SELECT * FROM two_drops WHERE tier_one='$drop_var'") 
    or die(mysql_error());

      while($drop_2 = mysql_fetch_array( $result )) 

        {
           echo '<option value="'.$drop_2['tier_two'].'">'.$drop_2['tier_two'].'</option>';
        }

}

My issue is how to modify the Java script to enable this

0

I think this should do the trick:

var selectOneID = 'mySelectOne'; // First select, when this changes the select two will be reloaded
var selectTwoID = 'mySelectTwo'; // Second select, reloaded when the first changes

$(function() { // On DOM Loaded

    $.get("func.php", { // Request the options for the first select
        func: "getTierOne",
        drop_var: ""
    }, function(options) { 
        $("#" + selectOneID) // Get the object for the first select
            .html(options) // Set the options returned
            .unbind('change') // Clean any change listener
            .change(function() { // Add a change event listener
                // When the change occurs the second select will be loaded

                var selectedValue = $(this).val(); // Gets the selected value from the first select

                $.get("func.php", { // Request the options for the second select
                    func: "drop_1",
                    drop_var : selectedValue
                }, function(options2) {

                    $("#" + selectTwoID).html(options2); // Sets the options returned

                });

            });
    });

});

Just set the selectOneID and the selectTwoID for the ID's of the selects. In the exemple it would be:

<select id="mySelectOne" size="1"></select>
<select id="mySelectTwo" size="1"></select>

Edited by AleMonteiro

0

Many thanks for all your effort, I have changed this for my use but cannot get it to work, please see below:

My Html section:

        <div>

            <label for="PhoneMake">Phone Make</label>     
               <select name="PhoneMake" id="PhoneMake">

              </select> 
        </div>

        <div>
            <label for="PhoneModel">Phone Model</label>    
                <select name="PhoneModel" id="PhoneModel">

            </select>
        </div>

My Php section (getModels.php):

<?php
//**************************************
//     Page load dropdown results     //
//**************************************
function getMake()
{
        include_once('./includes/dbinfo.inc');
    $result = mysql_query("SELECT DISTINCT Make FROM tblphones") 
    or die(mysql_error());

      while($x = mysql_fetch_array( $result )) 

        {
           echo '<option value="'.$x['Make'].'">'.$x['Make'].'</option>';
        }

}

//**************************************
//     First selection results     //
//**************************************

if($_GET['func'] == "getModel" && isset($_GET['func'])) { 
   getModel($_GET['drop_var']); 
}

function getModel($selectedValue)
{  
        include_once('./includes/dbinfo.inc');
    $result = mysql_query("SELECT * FROM tblphones WHERE Make='$selectedValue'") 
    or die(mysql_error());

      while($x = mysql_fetch_array( $result )) 

        {
           echo '<option value="'.$x['Model'].'">'.$x['Model'].'</option>';
        }

}

The Script between my <head> tags:

<script type="text/javascript">

var PhoneMake = 'PhoneMake'; // First select, when this changes the select two will be reloaded
var PhoneModel = 'PhoneModel'; // Second select, reloaded when the first changes
$(function() { // On DOM Loaded
    $.get("getModels.php", { // Request the options for the first select
        func: "getMake",
        drop_var: ""
    }, function(options) { 
        $("#" + PhoneMake) // Get the object for the first select
            .html(options) // Set the options returned
            .unbind('change') // Clean any change listener
            .change(function() { // Add a change event listener
                // When the change occurs the second select will be loaded
                var selectedValue = $(this).val(); // Gets the selected value from the first select
                $.get("getModels.php", { // Request the options for the second select
                    func: "getModel",
                    drop_var : selectedValue
                }, function(options2) {
                    $("#" + PhoneModel).html(options2); // Sets the options returned
                });
            });
    });
});
</script>

The first drop down "getMake" does not even populate with the results, Have I perhaps edited something incorrectly.

0

Many thanks for all your effort, I have changed this for my use but cannot get it to work, please see below:

My Html section:

        <div>

            <label for="PhoneMake">Phone Make</label>     
               <select name="PhoneMake" id="PhoneMake">

              </select> 
        </div>

        <div>
            <label for="PhoneModel">Phone Model</label>    
                <select name="PhoneModel" id="PhoneModel">

            </select>
        </div>

My Php section (getModels.php):

<?php
//**************************************
//     Page load dropdown results     //
//**************************************
function getMake()
{
        include_once('./includes/dbinfo.inc');
    $result = mysql_query("SELECT DISTINCT Make FROM tblphones") 
    or die(mysql_error());

      while($x = mysql_fetch_array( $result )) 

        {
           echo '<option value="'.$x['Make'].'">'.$x['Make'].'</option>';
        }

}

//**************************************
//     First selection results     //
//**************************************

if($_GET['func'] == "getMake" && isset($_GET['func'])) { 
   getMake($_GET['selectedValue']); 
}

function getModel($selectedValue)
{  
        include_once('./includes/dbinfo.inc');
    $result = mysql_query("SELECT * FROM tblphones WHERE Make='$selectedValue'") 
    or die(mysql_error());

      while($x = mysql_fetch_array( $result )) 

        {
           echo '<option value="'.$x['Model'].'">'.$x['Model'].'</option>';
        }

}

The Script between my <head> tags:

<script type="text/javascript">

var PhoneMake = 'PhoneMake'; // First select, when this changes the select two will be reloaded
var PhoneModel = 'PhoneModel'; // Second select, reloaded when the first changes
$(function() { // On DOM Loaded
    $.get("getModels.php", { // Request the options for the first select
        func: "getMake",
        drop_var: ""
    }, function(options) { 
        $("#" + PhoneMake) // Get the object for the first select
            .html(options) // Set the options returned
            .unbind('change') // Clean any change listener
            .change(function() { // Add a change event listener
                // When the change occurs the second select will be loaded
                var selectedValue = $(this).val(); // Gets the selected value from the first select
                $.get("getModels.php", { // Request the options for the second select
                    func: "getModel",
                    drop_var : selectedValue
                }, function(options2) {
                    $("#" + PhoneModel).html(options2); // Sets the options returned
                });
            });
    });
});
</script>

I managed to get the first drop down "getMake" to populate with the results, It does not effect the second drop down though , havee I perhaps edited something incorrectly.

0

I think I know what the error is.

The Variable selectedvalue is not being passed to my php function. how do I fix that?

0

fabzter, the variable passed to the php is 'drop_var', which has the value of the selectedValue.

$.get("getModels.php", { // Request the options for the second select
                    func: "getModel",
                    drop_var : selectedValue // the param name is 'drop_var'
                }

You can either change the php to get 'drop_var' or edit the javascript and change 'drop_var' to 'selectedValue'

Edited by AleMonteiro

0

yes thank you sooooo much, I managed to figure that out, how would I then keep that in a session on the page with the select as currently if you refresh the page the dropdowns refresh.

this definitely works but with a little flaw ...

let me explain...

if a user enters data on the form and lets say forgets to fill in a field and clicks submit it will validate and bounce back and all the data entered by the user is still available on the form so the user just fills out what they missed instead of retyping everything.

I normally keep that info in sessions, but beacuse of the way the chained select works currently it just resets.

I would normally have sonmething like this:

<label for="PhoneMake">Phone Make</label>     
               <select name="PhoneMake" id="PhoneMake">
               <option><?php print $_SESSION['PhoneMake']?></option>
               </select> 
0

You could do something like this:

<script type="text/javascript">

var PhoneMake = 'PhoneMake'; // First select, when this changes the select two will be reloaded
var PhoneModel = 'PhoneModel'; // Second select, reloaded when the first changes

var selectedPhone = '<?php print $_SESSION['PhoneMake']?>'; // Gets the value stored in the session
var selectedPhoneModel = '<?php print $_SESSION['PhoneModel']?>';

$(function() { // On DOM Loaded
    $.get("getModels.php", { // Request the options for the first select
        func: "getMake",
        drop_var: ""
    }, function(options) { 
        $("#" + PhoneMake) // Get the object for the first select
            .html(options) // Set the options returned
            .unbind('change') // Clean any change listener
            .change(function() { // Add a change event listener
                // When the change occurs the second select will be loaded
                var selectedValue = $(this).val(); // Gets the selected value from the first select
                $.get("getModels.php", { // Request the options for the second select
                    func: "getModel",
                    drop_var : selectedValue
                }, function(options2) {

                    $("#" + PhoneModel).html(options2); // Sets the options returned

                    // After loading the options, verify if there is one already selected
                    if ( selectedPhoneModel != '' ) {
                        $("#" + PhoneModel') // Gets the object for the phone model select
                            .val(selectedPhoneModel) // Sets it's value as the selected phone model in the session      
                    }
                });
            });

        // After loading the options, verify if there is one already selected
        if ( selectedPhone != '' ) {
            $("#" + PhoneMake) // Gets the object for the phone select
                .val(selectedPhone) // Sets it's value as the selected phone in the session
                .change(); // Simulates a change so it will load the models options
        }
    });
});
</script>

I normally prefer to use AJAX to make the submit, cause this way the page isn't refresh and the selections are never lost.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.