ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Refreshing a dropdown list when selecting another dropdown list.

August 18, 2008 4:44am

Subscribe [10]
  • #1 / Aug 18, 2008 4:44am

    theighost

    19 posts

    hi,

    I am using codeigniter for a site and need to make a script that makes the following :

    I have a dropdown list named “states” for example,and another drop down list named “cities”.

    I want when i select a state the “cities” dropdown list to refresh automaticly,showing the cities in the state selected.

    I saw many scripts on the net…but they were not for codeiginter and they were using the method get, which i dont really know how to apply it in codeigniter.

    BTW the states and the cities are taken from a database and are not static info.

    any help would be appreciated.

  • #2 / Aug 18, 2008 5:03am

    xwero

    4145 posts

    This can only be done using javascript. If you want this in php there is another action needed, for instance a button that submits the states selection.

    Changing get urls to CI urls can be done by replacing the key-value pairs with segments: site.com/show?cities=1 -> site.com/show/cities/1. This change is done in javascript.

  • #3 / Aug 18, 2008 7:40am

    theighost

    19 posts

    yes i tried that, but the scripts that i tried written in ajax and when i tried to change them to look like site.com/show/cities/1, they didnt work.


    this is the original code:

    the file state.php:

    <?
        //set IE read from page only not read from cache
        header (“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
        header (“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
        header (“Cache-Control: no-cache, must-revalidate”);
        header (“Pragma: no-cache”);
       
        header(“content-type: application/x-javascript; charset=tis-620”);
       
        $data=$_GET[‘data’];
        $val=$_GET[‘val’];
       
        //set database
    $dbhost = “localhost”;
    $dbuser = “”;
    $dbpass = “”;
    $dbname   = “test”;
    mysql_pconnect($dbhost,$dbuser,$dbpass) or die (“Unable to connect to MySQL server”); 
       
        if ($data==‘states’) { // first dropdown
    echo "<select name='states'>\n";
    echo "<option value='0'>==== choose state ====</option>\n";
    $result=mysql_db_query($dbname,"select `id`, `state` from states order by `state`");
    while(list($id, $name)=mysql_fetch_array($result)){
    echo "<option value=\"$id\" >$name</option> \n" ;
    }
        } else if ($data==‘cities’) { // second dropdown
    echo "<select name='cities' >\n";
    echo "<option value='0'>====choose cities ====</option>\n";
    $result=mysql_db_query($dbname,"SELECT `id`, `city` FROM cities WHERE `state_id` = '$val' ORDER BY `city` ");
    while(list($id, $name)=mysql_fetch_array($result)){
    echo "<option value=\"$id\" >$name</option> \n" ;
    }
        }
        echo “</select>\n”; 
    ?>

     

    The second file state_dropdown.php:


    <?   
        echo “<form name=sel>\n”;
        echo “States : <font id=states><select>\n”;
        echo “<option value=‘0’>============</option> \n” ;
        echo “</select></font>\n”;
       
        echo “Cities : <font id=cities><select>\n”;
        echo “<option value=‘0’>=== none ===</option> \n” ;
        echo “</select></font>\n”;
    ?>

    [removed]
    function Inint_AJAX() {
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
    try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
    alert("XMLHttpRequest not supported");
    return null;
    };

    function dochange(src, val) {
    var req = Inint_AJAX();
    req.onreadystatechange = function () {
    if (req.readyState==4) {
    if (req.status==200) {
    document.getElementById(src)[removed]=req.responseText; //retuen value
    }
          }
        };
        req.open(“GET”, “state.php?data=”+src+”&val;=”+val); //make connection
        req.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded;charset=iso-8859-1”); // set Header
        req.send(null); //send value
    }

    window.onLoad=dochange(‘states’, -1);      // value in first dropdown
    [removed]

     

     

     

    I changed the files (following in the next comment):

  • #4 / Aug 18, 2008 7:41am

    theighost

    19 posts

    the first file changed to:

    <?
        //set IE read from page only not read from cache
        header (“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
        header (“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
        header (“Cache-Control: no-cache, must-revalidate”);
        header (“Pragma: no-cache”);
       
        header(“content-type: application/x-javascript; charset=tis-620”);
       
        $data=$this->uri->segment(3);
        $data=$this->uri->segment(4);
         
        //set database
    $dbhost = “localhost”;
    $dbuser = “”;
    $dbpass = “”;
    $dbname   = “test”;
    mysql_pconnect($dbhost,$dbuser,$dbpass) or die (“Unable to connect to MySQL server”); 
       
        if ($data==‘states’) { // first dropdown
    echo "<select name='states'>\n";
    echo "<option value='0'>==== choose state ====</option>\n";
    $result=mysql_db_query($dbname,"select `id`, `state` from states order by `state`");
    while(list($id, $name)=mysql_fetch_array($result)){
    echo "<option value=\"$id\" >$name</option> \n" ;
    }
        } else if ($data==‘cities’) { // second dropdown
    echo "<select name='cities' >\n";
    echo "<option value='0'>====choose cities ====</option>\n";
    $result=mysql_db_query($dbname,"SELECT `id`, `city` FROM cities WHERE `state_id` = '$val' ORDER BY `city` ");
    while(list($id, $name)=mysql_fetch_array($result)){
    echo "<option value=\"$id\" >$name</option> \n" ;
    }
        }
        echo “</select>\n”; 
    ?>


    the second changed to :


    <?   
        echo “<form name=sel>\n”;
        echo “States : <font id=states><select>\n”;
        echo “<option value=‘0’>============</option> \n” ;
        echo “</select></font>\n”;
       
        echo “Cities : <font id=cities><select>\n”;
        echo “<option value=‘0’>=== none ===</option> \n” ;
        echo “</select></font>\n”;
    ?>

    [removed]
    function Inint_AJAX() {
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
    try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
    alert("XMLHttpRequest not supported");
    return null;
    };

    function dochange(src, val) {
    var req = Inint_AJAX();
    req.onreadystatechange = function () {
    if (req.readyState==4) {
    if (req.status==200) {
    document.getElementById(src)[removed]=req.responseText; //retuen value
    }
          }
        };
        req.open(“GET”, “state.php/”+src+”/”+val); //make connection
        req.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded;charset=iso-8859-1”); // set Header
        req.send(null); //send value
    }

    window.onLoad=dochange(‘states’, -1);      // value in first dropdown
    [removed]

     

    and it didnt work plz help

  • #5 / Aug 18, 2008 7:46am

    xwero

    4145 posts

    Check in firebug if the url is correct. I’m guessing it’s not because you have no state.php file in CI everything goes via the index.php file so your url will be something like index.php/state/”+src+”/”+val

  • #6 / Aug 18, 2008 8:23am

    theighost

    19 posts

    I’ve tried in every way now…its not working…there must be something missing…it doesnt even show any state in the dropdown menu although everything is written properly!

  • #7 / Aug 18, 2008 8:36am

    xwero

    4145 posts

    did you check if the controller is outputting the cities? In other words what does site.com/index.php/state/src/val gives you?

    I’m not an ajax specialist, i’m a jquery user 😊 Then your code looks like this

    $('#states').change(function(){ // do when element with the id states changes
      // get the values you need for the url
      var val = $(this).val();
      var src = $(this).attr('id');
    
      $.ajax({ 
       url: "index.php/state/"+src+"/"+val, // build url
       success: function(msg){ // do if the ajax request is successful
         $('#cities').html(msg); // add server generated html to the element with the id cities
       }
      });
    
    });

    As you see it’s a bit more readable than your javascript snippet that handles the XMLHttp object directly.

  • #8 / Aug 18, 2008 8:58am

    theighost

    19 posts

    yes i did that before and it has the same result…

    you’re code is little hard… i shall paste it instead of the “dochange()” function right?

    and by the way i am not using site.com/index.php/state/src/val

    but site.com/admin/controller_class/function(state)/state_dropdown/src/val

  • #9 / Aug 18, 2008 9:14am

    xwero

    4145 posts

    It’s not copy’n'paste code. It’s meant as an example how it’s done with jquery. Because you find it difficult i heavy documented it. And removed a line that wasn’t needed.

    The url too was meant as an example.

  • #10 / Aug 18, 2008 9:24am

    theighost

    19 posts

    yep i know that i should change it to my case…anyway its really strange that the dropdown list doesnt show anything….if the problem was in refreshing it would have been normal…but actually it doesn’t take the values from the database(not likely) or the state.php doesn’t run (likely) which contains the sql query!

  • #11 / Aug 18, 2008 9:30am

    xwero

    4145 posts

    You can do a check in the javascript code to see what the url looks like maybe that is the problem.

    var my_url = "index.php/state/"+src+"/"+val;
    alert(my_url);
    // ...
    url: my_url,
    // ...
  • #12 / Aug 18, 2008 9:43am

    theighost

    19 posts

    I AM GOING CRAZY the javascript is getting ignored or something….nothing appears but the HTML of the two empty dropdown lists!

    not even an alert is not appearing!

  • #13 / Aug 18, 2008 9:45am

    xwero

    4145 posts

    You build the states list using ajax?

  • #14 / Aug 18, 2008 9:50am

    theighost

    19 posts

    nope it uses php as u can see this script works on the localhost using normal php(not codeigniter)

  • #15 / Aug 18, 2008 10:06am

    xwero

    4145 posts

    Then you have two problems as i get out of you responses:

    1 : the states dropdown doesn’t add the state options to the states dropdown (php problem)
    2 : the change event of the dropdown doesn’t get registered (javascript problem)

    The first thing you have to do is to check where it goes wrong with the php code, this might be a solution to the ajax generated options problem too if you use similar code.
    And then you need to check/code in javascript to registration of the change event.

    Without more code i can’t help you further. But if you do post code please wrap it in the bbcode tag code this make reading a bit easier as i’m used to the highlighting.

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases