SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist BJ Duncan's Avatar
    Join Date
    Jun 2007
    Location
    North Richmond
    Posts
    495
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    What am I doing wrong?

    Hi all,

    I am new to javascript as I generally use php. I have recently tried to give javascript a go with a form that has 3 drop downs and with each drop down is pulled from a MySQL database using php.

    Can someone please help me, this is what I have at the moment:

    Code JavaScript:
    function reload(form)
    {
    var val=form.country_id.options[form.country_id.options.selectedIndex].value; 
    self.location='sample.php?countryId=' + val ;
    }
     
    function reload3(form)
    {
    var val=form.country_id.options[form.country_id.options.selectedIndex].value; 
    var val2=form.state_id.options[form.state_id.options.selectedIndex].value; 
     
    self.location='sample.php?countryId=' + val + '&stateId=' + val2 ;
    }

    PHP Code:
    <h2>Job Search</h2>
                    <div class="entry">
                        <p>
                        <form name="form" action="" method="">
                        <fieldset><legend>Job Search</legend>
                        <?php
                        
    ### Create the queries for the drop-down menus ###
                        ### Getting the data from Mysql table for first list box ###
                        
    $quer2 mysql_query("SELECT DISTINCT country_id,country FROM country order by country ASC"); 
                        
    ### End of query for first list box ### 
                        ### for second drop down list we will check if country is selected else we will display all the states ###  
                        
    $country $_GET['country_id']; 
                        if (isset(
    $country)) {
                            
    $quer mysql_query("SELECT DISTINCT state,state_id FROM state where country_id=$country order by state"); 
                        } else {
                            
    $quer mysql_query("SELECT DISTINCT state,state_id FROM state order by state"); 
                        } 
                        
    ### End of query for second subcategory drop down list box ###
                        ### for Third drop down list we will check if state is selected else we will display all the cities///// 
                        
    $state $_GET['state_id'];
                        if (isset(
    $state)) {
                            
    $quer3 mysql_query("SELECT DISTINCT city FROM city where state_id = $state order by city");
                        } else {
                            
    $quer3=mysql_query("SELECT DISTINCT city FROM city order by city"); 
                        }
                        
    ### End queries for drop-down menu ###
                        
                        ### Starting of first drop downlist ###
                        
    echo "Country: <select name='country' onchange=\"reload(this.form)\"><option value=''>[Anywhere]</option>";
                        while (
    $selection mysql_fetch_array($quer2)) {
                            if (
    $selection['country_id'] == @$country) {
                                echo 
    "<option selected value='$selection[country_id]'>$selection[country]</option><br />";
                            } else {
                                echo  
    "<option value='$selection[country_id]'>$selection[country]</option>";
                            }
                        }
                        echo 
    "</select>";
                        
    ### This will end the first drop down list ###
                        
    echo "<br /><br />";
                        
    ### Starting of second drop downlist ###
                        
    echo "State: <select name='state' onchange=\"reload3(this.form)\"><option value=''>[Any State]</option>";
                        while(
    $nextSelection mysql_fetch_array($quer)) {
                            if (
    $nextSelection['state_id'] == @$state) {
                                echo 
    "<option selected value='$nextSelection[state]'>$nextSelection[state]</option><br />";
                            } else {
                                echo  
    "<option value='$nextSelection[state_id]'>$nextSelection[state]</option>";
                            }
                        }
                        echo 
    "</select>";
                        
    ###  This will end the second drop down list ###
                        
    echo "<br /><br />";
                        
    ### Starting of third drop downlist ###
                        
    echo "City: <select name='city' ><option value=''>[Any City]</option>";
                            while(
    $nextSelection mysql_fetch_array($quer3)) {
                                echo  
    "<option value='$nextSelection[city]'>$nextSelection[city]</option>";
                            }
                        echo 
    "</select>";
                        
    ###  This will end the third drop down list ###
                        
    echo "<br /><br />";
                        
    ?>
    My error is that when I make the first selection of the country, the country_id goes into the URL but the 2nd drop down doesn't narrow down to the options for the selected country.
    Regards,
    BJ Duncan

  2. #2
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Argh, that's tough ****! I tried to do the same thing a month ago, and ended up using JSON, as it was the only smooth, painless (ok, that's relative) solution for something that should be so simple. Here's my code for that:

    The javascript:
    Code JavaScript:
    <script type="text/javascript">
     
                   function item_selected() {
                      var oSelect = document.getElementById('slct_cat');
                      var sVal = oSelect.value;
    				  var lang = get_arg_val("lang");
    					var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP.3.0');
        	              req.open('GET', 'menu.php?lang=' + lang + '&op=get_second_dropdown&selected_item=' + sVal, true);
            	          req.onreadystatechange = function (aEvt) {
                	        if (req.readyState == 4) {
                    	       if(req.status == 200)
                        	    create_second_dropdown(req.responseText);
    	                       else
        	                    alert('Error loading data');
            	            }
                	      };
                      req.send(null);					  
                   }
     
     
     
                   function create_second_dropdown(sResponseText) {
                      var oSelect = document.getElementById('slct_prod');
     
                      // Remove all the existing option elements
                      while (oSelect.hasChildNodes()) { oSelect.removeChild(oSelect.firstChild); }
                      var aValues = eval(sResponseText);
    				  var array = new Array();
     
                      for (var i=0, len=aValues.length; i < len; i++) {
                         var oOption = document.createElement('option');
    				  	 array = aValues[i].split("=>");
    					 oOption.innerHTML = array[0];
    					 oOption.value = array[1];
     
                         oSelect.appendChild(oOption);
                      }
                   }
     
     
     
    			function prod_selected() {
    				var oSelect_prod = document.getElementById('slct_prod');
    				var oSelect_cat = document.getElementById('slct_cat');
    				var sVal_prod = oSelect_prod.value;
    				var sVal_cat = oSelect_cat.value;
     
    				var prod_index = oSelect_prod.selectedIndex;
    				var cat_index = oSelect_cat.selectedIndex;
     
    				var prod_name = oSelect_prod.options[prod_index].text;
    				var cat_name = oSelect_cat.options[cat_index].text;
     
    				var lang = get_arg_val("lang");
    				if (lang == false) lang = "nl";
     
    				var url = lang + "/catalog/" +  prod_name;
    				if (sVal_prod > 0) window.location = "http://www.blue-wave.be/test/" + url;
    			}
     
     
     
    			function get_arg_val(arg) {
    				var url = document.URL;
    					var itm = url.split("/");
    					itm = itm[4];
    					return itm;
    			}
     
     
     
    </script>

    The extra PHP file (menu.php):
    PHP Code:
    <?php
    include_once("connection.php");
    session_start();

    function 
    get_second_dropdown($sFirst_Item) {
            
    $language $_GET["lang"];
            
    $language strip_tags($language);
            
    $language stripslashes($language);
            
    $language htmlspecialchars($language);
            
            if (empty(
    $language)) $language "nl";
            
            include(
    "languages/" $language "/interface.php");
            
            
    $lang "[" LANG_PRODUCTS "]";

            
    $lang_entry $lang '=>0';

            
            if (
    $sFirst_Item != "Blue-Wave") {
                
    $sql "SELECT id, " $language " FROM bw_prod_name WHERE cat = " $sFirst_Item;
                
    $sql mysql_query($sql);

                
    $array = array($lang_entry);
                while(list(
    $id$name) = mysql_fetch_array($sql)) {
                    
    $key $name '=>' $id;
                    
    array_push($array$key);
                }
       
               
    // Start the JSON array output
               
    echo "{['";

                     echo 
    implode("','"$array);
       
       
               
    // End the JSON array output
               
    echo "']}";
            }
            else echo 
    "{['" $lang "']}";

       return 
    true;
    }




    $item $_REQUEST['selected_item'];
    $item strip_tags($item);
    $item stripslashes($item);
    $item htmlspecialchars($item);

    switch(
    $_REQUEST['op']) {
       case 
    "get_second_dropdown":
            
    get_second_dropdown($item);
            break;
       default:
            
    header("Location: index.php");
            break;
    }


    ?>
    The menu itself:
    PHP Code:
                <form name="frm_prod" id="frm_prod" action="http://www.blue-wave.be/test/';
                if (
    $file != "") echo $file . '/'; 
                echo 
    $args .  '" method="post">
                    <
    select id="slct_cat" name="slct_cat" onchange="item_selected()">
                        <
    option value="Blue-Wave">[Blue-Wave]</option>';

    $sql = "SELECT id, " . $_SESSION["lang"] . " FROM bw_prod_cat";
    $sql = mysql_query($sql);

    while (list($id, $name) = mysql_fetch_array($sql)) 
        echo '
    <option value="' . $id . '">' . $name . '</option>';

         echo '
    </select>
                    <
    select id="slct_prod" name="slct_prod" onchange="prod_selected()">
                        <
    option value="0">[' . LANG_PRODUCTS . ']</option>';
                        fill_products();
                    echo '
    </select>
                    <
    noscript><input type="submit" name="sbmt_menu" value="Go" /></noscript
    Mind you, some things (like that $file variable) aren't necessary for what you're trying to do.

  3. #3
    SitePoint Evangelist BJ Duncan's Avatar
    Join Date
    Jun 2007
    Location
    North Richmond
    Posts
    495
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Kon-Tiki,

    Thanks for your time. I will certainly utilise your code if that is ok. This is giving me such a headache! - The joys of it all. - Thanks mate
    Regards,
    BJ Duncan

  4. #4
    SitePoint Member
    Join Date
    Nov 2007
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    <?php
    //define a php function that runs and echoes your mysql query as an inc.php page

    function call_eastcap(){

    //mysql connect etc.

    //stores selection as variable
    $query = "SELECT province, town FROM towns where province='Eastern Cape'";

    //retrieves data from table and store into $result
    $result = mysql_query($query)
    or die(mysql_error());


    //stores $result into $row
    while ($row = mysql_fetch_array($result))
    {
    //this next code echoes towns i.e. mysql_array[1]
    echo "<a href='www.$row[1]'>$row[1]</a>";
    echo "<br/>";
    }
    }
    ?>
    //once you have defined your function...
    //stay on same page and add some of the sort...
    //which calls your function
    <DIV>
    <?php call_eastcap()
    ?>
    </DIV>


    //then on whatever page you need to run this within a drop down do something like this

    <SCRIPT type=text/javascript>
    <!--
    function openclose(list) {
    var more = document.getElementById(list);
    if ( more.style.display != "none" ) {
    more.style.display = 'none';
    } else {
    more.style.display = '';
    } } //-->
    </SCRIPT>

    <DIV id="main" onClick="openclose('dropdiv');">
    Eastern Cape

    <DIV id="dropdiv" style='display:none'>
    //it is important to set display none here otherwise it will open on page load...i used a click event...if you use a mouseover/out you don't have to worry about this...
    //then just include your other php in this 'sub'div!!!
    <?php
    include("whatever.php");
    ?>
    </DIV>
    </DIV>

    very simple!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •