Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

dynamic drop down boxes

  • 28-04-2008 10:21am
    #1
    Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭


    hey guys,

    i want to create a page that has three drop down boxes on it.

    they will all need to be filled by a mySql query (not a problem) but here's where my problem starts (in my head thinking anyways :p)

    i have the first box populated by something like this:

    SELECT projectName from projects

    i want the second box then to be populated by something like this:

    SELECT projectNumber from project WHERE projects = '<what the user selected in box 1>'.

    then similarly for the third box i want it to be populated by a query like so:

    SELECT status FROM projects WHERE project='<what the user picked in box 1>' && projectNumber ='<what the user picked in box2>'.

    and then to create a query that will implement all the above choices.

    SELECT * FROM projects WHERE project='value1' && projectNumber='value2' && status='value3'.

    i'm using php to access the database.

    any help is greatly appreciated.


Comments

  • Registered Users, Registered Users 2 Posts: 18,272 ✭✭✭✭Atomic Pineapple


    have a similiar problem myself in Java at the minute, tried searching the net and sun and countless java forums and no solution seemed to work, In the end the deadline for my project ended and I didnt get it done, so I'm also interested in a solution to this, sorry I cant be of any help


  • Registered Users, Registered Users 2 Posts: 8,488 ✭✭✭Goodshape


    I did something similar recently, using Javascript to call a PHP function based on the list item selected, which then returns a second list (or input box.. or, actually, whatever you want it to).

    This was my solution :

    HTML :
    <select name="r1" onchange="searchSelect(this.value,'1');">
    	<option value="">(Please Select)</option>
    	<option value="1" SELECTED>Option 1</option>
    	<option value="4" >Option 2</option>
    	<option value="3" >Option 3</option>
    	<option value="2" >Option 4</option>
    	<option value="5" >Option 5</option>
    </select>
    
    <div id="searchRowInner1">&nbsp;</div>
    
    

    The above HTML will pass the value of the select option (numbers 1 to 5) and the number 1 (which relates to searchRowInner1) to the Javascript funtion, searchSelect.


    Javascript :
    function searchSelect(thevar,rownum)
      {
      var xmlHttp;
      var nextrow;
      nextrow = rownum + 1;
      try
        {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
        }
      catch (e)
        {
        // Internet Explorer
        try
          {
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
          try
            {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
          catch (e)
            {
            alert("Your browser does not support AJAX!");
            return false;
            }
          }
        }
        xmlHttp.onreadystatechange=function()
          {
          if(xmlHttp.readyState==4)
            {
             document.getElementById('searchRowInner'+rownum).innerHTML=xmlHttp.responseText;
            }
          }
        xmlHttp.open("GET","index.php?t=searchSelect&rownum="+rownum+"&qs="+thevar,true);
        xmlHttp.send(null);
      }
    

    Then the Javascript sends those values to index.php as GET variables, and fills the correct row with the HTML generated as a result. Simple if ($_GET == 1) style stuff exists within index.php ...which should allow you to run the correct SQL query, or do whatever else you need to, before generating new HTML.

    It's a bit rough and ready as it is but it could give you a starting point, or at least demonstrate one possible method.


    //edit
    In my generated HTML I also included a new select box with a new searchRowInner and incrementally increased the searchRowInner number and any other number relating to it -- meaning the javascript can then fill in searchRowInner2, searchRowInner3, etc.


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    hmm, was kind of thinking and hoping it there'd be a non ajax solution, i've never done it before and i'm not the best at javascripting either.

    i took a tutorial off w3schools and i'm working on something at the moment, i've got a feeling i should get it working but if not i shall be back.

    Thanks guys.


  • Registered Users, Registered Users 2 Posts: 3,428 ✭✭✭randombar


    Hi Cremo,
    I reckon I'd have about the same knowledge as yourself at the javascript.
    I would really recommend getting into the ajax, helps a lot and really isnt that difficult to get your head around even with basic javascript knowledge!
    Gary


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    You can do it without AJAX, but it involves refreshing the whole page, which is viewed as nasty nowadays.....

    My recommendation is to do it with AJAX, but basically the non-AJAX version has an onclick that submits the form to the same page, sets the currently-selected item in the box the user clicked on and loads the second select box (if the appropriate GET variable is set).

    Not pretty, but it works.

    P.S. Check out jQuery for doing AJAX calls much easier!!!


  • Advertisement
  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    Yep, basically your options are AJAX or pages being resent with each drop down selection which, as has been stated, is considered fairly nasty. On top of which, using the page refresh method will still require javascript, unless you want your users to have to select an option and then hit a submit button to send the page, which is even uglier. So your best option is AJAX imo, and isbecoming more and more mainstream these days and needs to be embraced rather than shied away from.


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    Mirror wrote: »
    On top of which, using the page refresh method will still require javascript, unless you want your users to have to select an option and then hit a submit button to send the page, which is even uglier.

    That last bit isn't really an issue, Mirror, as AJAX will require JavaScript anyways....


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    Liam Byrne wrote: »
    That last bit isn't really an issue, Mirror, as AJAX will require JavaScript anyways....
    Ah, this was my point, the choice was either the three refreshes or two javascript based alternatives, with AJAX being the more user friendly option imo. I went for dinner half way through the post so probably didn't make as much sense as I had hoped!


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    Mirror wrote: »
    Ah, this was my point, the choice was either the three refreshes or two javascript based alternatives, with AJAX being the more user friendly option imo. I went for dinner half way through the post so probably didn't make as much sense as I had hoped!

    So, to clarify :

    Preferred Option:
    AJAX (i.e. Javascript) with no page refresh

    Option 2:
    onchange trigger (i.e. Javascript) to refresh page (probably the preferred method pre-ajax)

    Option 3:
    select + submit button to refresh page

    What I was getting at, though, is that if you have JavaScript I wouldn't really bother considering Option 2 at all......I only said it because it was specifically asked if AJAX was the only option.

    Option 3 is even messier/less intuitive than Option 2, and should be the immediate "forget about this one", but as Mirror said it's probably useful as a no-JavaScript fallback, if one is required....


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Cremo you should learn AJAX - it is surprizenly easy and very repeatitive once you know it once. You'll have AJAX learned in the time you spend messing with another solution and you can use AJAX in later projects :)


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    lol i've nothing against AJAX it was just i thought with a problem like this - which is so common in web dev - that there might of been a more easier solution.

    i've started the AJAX i'm running into a little bit of a snag.

    i have the first drop down list working perfectly, giving me a list of projects.

    when a user selects a project a second drop down list appears containing a list of certain products that are associated with that project.

    when a user selects from the second drop down list, a table is displayed (showTable.php).

    this works grand but the only problem is that the select drop down box disappears when i select from the second box.

    here's my code

    ajaxexample.php: (site i call the ajax from).
    [php]
    <?php
    include 'dbconnect.inc.php';
    echo '<html>
    <head>
    <script src="select.js"></script>
    </head>
    <body>

    <form>
    ' . selectProjectBox() . '
    </form>

    <p>
    <div id="txtHint"><b>User info will be listed here.</b></div>
    </p>

    </body>
    </html>';




    //
    //PHP function to display drop down box.
    //
    //

    function selectProjectBox()
    {
    $query = "SELECT project FROM trs GROUP BY project";
    echo "<select id=\"project\" onchange=\"showProduct(this.value)\">\n<option selected=\"Selected\">-</option>\n";
    $result = mysql_query($query) or die ( mysql_error() );
    while( $row = mysql_fetch_array($result) )
    {
    $selectOption = $row;
    $html.="<option id=\"$selectOption\">$selectOption</option>\n";
    }
    $html.="</select>\n";
    echo $html;
    }
    [/php]


    select.js: (my ajax script).
    var xmlHttp
    
    function showProduct(project)
    { 
    	xmlHttp=GetXmlHttpObject()
    	if (xmlHttp==null)
    	{
     		alert ("Browser does not support HTTP Request")
     		return
    	}
    
    	var url="showTable.php"
    	url=url+"?project="+project
    	url=url+"&sid="+Math.random()
    	xmlHttp.onreadystatechange=stateChanged 
    	xmlHttp.open("GET",url,true)
    	xmlHttp.send(null)
    }
    
    function showTable()
    {
    	var project = document.getElementById("project").value;
    	var product = document.getElementById("product").value;
    
    	xmlHttp =  GetXmlHttpObject();
    	if(xmlHttp == null)
    	{
    		alert("Browser does not support HTTP Request");
    		return;
    	}
    	
    	var url = "showTable.php";
    	url=url+"?project="+project+"&product="+product;
    	url=url+"&sid="+Math.random();
    	xmlHttp.onreadystatechange=stateChanged ;
    	xmlHttp.open("GET",url,true);
    	xmlHttp.send(null);
    }
    
    function stateChanged() 
    { 
    	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    	{ 
    		document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
    	} 
    }
    
    function GetXmlHttpObject()
    {
    	var xmlHttp=null;
    	try
     	{
     		// Firefox, Opera 8.0+, Safari
     		xmlHttp=new XMLHttpRequest();
     	}
    	catch (e)
     	{
     		//Internet Explorer
     		try
      		{
      			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      		}
     		catch (e)
      		{
      			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
     	 	}
     	}
    	return xmlHttp;
    }
    

    showTable.php: (populates the second drop down list and displays table when a option is selected from second list).
    [php]
    <?php

    include 'dbconnect.inc.php';
    include 'header.html';

    $project=$_GET["project"];
    $product=$_GET["product"];

    if( isset($project) && !( isset($product)) )
    {
    $sql="SELECT product FROM project WHERE project = '".$project."' GROUP BY product";

    $result = mysql_query($sql);

    echo "<select id=\"product\" onchange=\"showTable()\">\n<option selected=\"selected\">-</option>\n";

    while($row = mysql_fetch_array($result))
    {
    $selectOption = $row;
    $html.="<option id=\"$selectOption\">$selectOption</option>\n";
    }

    }

    $html.="</select>\n";
    echo $html;





    if( isset($project) && isset($product) )
    {
    $query = "SELECT ID, project, product, productNumber, slogan, origin, status, newstatus, submitDate FROM project WHERE project='$project' && product='$product'";

    $result = mysql_query($query) or die ( mysql_error() );

    //display the tr's in a table.
    echo '<div id="tr_div">
    <table class="stats sortable" id="tr_table">
    <tr>
    <td class="hed"><b>ID</b></td>
    <td class="hed"><b>Project</b></td>
    <td class="hed"><b>Product</b></td>
    <td class="hed"><b>Product No.</b></td>
    <td class="hed"><b>Slogan</b></td>
    <td class="hed"><b>Origination</b></td>
    <td class="hed"><b>Status</b></td>
    <td class="hed"><b>New Status</b></td>
    <td class="hed"><b>Submitted Date</b></td>
    </tr>
    ';
    while( $row = mysql_fetch_array($result) )
    {
    echo "<tr><td>" . $row . "</td><td>" . $row . "</td><td>" . $row . "</td><td>" . $row . "</td><td nowrap=\"nowrap\">" . $row . "</td><td>" . $row . "</td><td>" . $row . "</td><td>" . $row . "</td><td>" . $row . "</td></tr>\n" ;
    }
    echo "</table>";
    }
    ?>
    [/php]


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    You are forgetting your simi colons here:
    	xmlHttp.onreadystatechange=stateChanged 
    	xmlHttp.open("GET",url,true)
    	xmlHttp.send(null)
    

    This could cause javascript error setting the content of the Div to nothing hense why table dissapears. Open the Error console on Firefox to see what is going on.


    Edit - you appear to be missing lots of simi-colons :) - I'm sure you've noticed that :P


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    Webmonkey wrote: »
    You are forgetting your simi colons here:
    	xmlHttp.onreadystatechange=stateChanged 
    	xmlHttp.open("GET",url,true)
    	xmlHttp.send(null)
    

    This could cause javascript error setting the content of the Div to nothing hense why table dissapears. Open the Error console on Firefox to see what is going on.


    Edit - you appear to be missing lots of simi-colons :) - I'm sure you've noticed that :P
    Just because I'd be embarrassed if it were me... - It's semi - colons :)


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    yup i knew those semi-colons were missing :p

    it's not the table that disappears, it's the second drop down box,

    i've modified from my previous question with 3 boxes to just two so it's now like this.

    select box 1 >> select a project.
    select box 2 >> select a product (populated depending on select in box 1)

    print table of information.

    i've attached some images to clear this up:

    1.bmp - this is that starting point.

    2.bmp - this is after user selects from first box.

    3.bmp - this is after user selects from second box


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    It's quite simple really. Look at your file showTable.php. You have specified that if project is set and product is not, then display the second select box. You then go on to say if both are set, display the table. So the criteria required to display the table (i.e. product being set) is actually preventing the select box from being displayed because it requires product to not be set. Just check that $project is set on the first if() statement, should solve your problem.


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Mirror wrote: »
    Just because I'd be embarrassed if it were me... - It's semi - colons :)
    I can't spell :(


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    lol i had just noticed that about 30 seconds ago, d'oh.

    all is well now guys, thanks.

    no doubt i'll probably be back with another problem soon.


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    No probs, good luck with it!


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    bit odd but this doesn't work in IE6 (needs too because i'm going to have ~50 people all using IE6 using it)

    when you select an option from the first box, the second box appears but doesn't get populated.

    is there any debugger i can get for IE? i have firebug for firefox and usually will put a warning or error there that when fixed will make the site work in IE but not so this time, all i'm getting are sucessful GET request confimations.


  • Registered Users, Registered Users 2 Posts: 568 ✭✭✭phil


    I haven't gone down through the code, so maybe someone can help you specifically, but IMHO in future get a Javascript library to cut down on the cross-browser issues and the learning curve associated with writing your own javascript from scratch.

    I can't recommend JQuery enough for this.


  • Advertisement
  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    I don't know js in the true sense of knowing, but a quick google gave me this:

    "In Internet Explorer, you create the object using new ActiveXObject("Msxml2.XMLHTTP") or new ActiveXObject("Microsoft.XMLHTTP") depending on the version of MSXML installed."

    Perhaps then, try the alternative ActiveXObject("Microsoft.XMLHTTP")?


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne




  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Depending on the amount of options the other way to do it would be to fill the selects with all options and group them (<optgroup label="group1">) according to their parent then use script on the client side to filter these results using arrays to hold the items for each group and so on. Ajax is fine but try turning of script in firefox on this site for example just to see how the web is slowly being strangled by it's over use. Also a topic rarely discussed in these forums is unobtrusive scripting. It would be really nice to see more people advocating it.


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    ok i found the problem (half the battle - other is to fix it :) ) it turns out that the value in the first select box isn't being passed to the javascript function using showProduct(this.value);

    totally strange


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    ok still having problems in IE 6.0

    i call a javascript function like so:
    <select id="project" name="project" onchange="showSubsystem(this.value);">
    *options go in here*
    </select>
    

    and i have the javascript function like so:
    showSubsystem(projectvalue)
    {
       alert(projectvalue);
    }
    

    when i run that i get an empty alert box. :( but when it comes to firefox i get an alert box with whichever value is inside projectvalue.

    can anyone shed any light on this as it's got me completely stumped.


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Much as I hate inline script I would suggest you try:-

    onchange="showSubsystem(this.options[this.selectedIndex].value);"


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    Try changing "this.value" to just "this" in the html.


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    musician wrote: »
    Much as I hate inline script I would suggest you try:-

    onchange="showSubsystem(this.options[this.selectedIndex].value);"

    when i use the above i get the same alert box as before.
    Mirror wrote: »
    Try changing "this.value" to just "this" in the html.

    when i use just "this" i get [Object] in the alert box.

    :confused:


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    How about showSubsystem(this); and

    showSubsystem(projectvalue)
    {
    alert(projectvalue.options[projectvalue.selectedIndex].value);
    }


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    musician wrote: »
    How about showSubsystem(this); and

    showSubsystem(projectvalue)
    {
    alert(projectvalue.options[projectvalue.selectedIndex].value);
    }

    nope still get the same, blank alert in IE non blank in FF.


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Well theres something very strange going on then. Want to post up your html/script?


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    O.k. I looked at your code above and you are not giving the options a value (assuming you are still using the same code) just an id and a text value so you could change the code to:-

    onchange="showSubsystem(this.options[this.selectedIndex].text);"

    Normally you would use the value of an option to match with an id field in a db and the text to match with the text field:-

    <option value="0">Select a Category</option>
    <option value="1">Category With ID of 1</option>

    I'm not sure what you need but if you do need the value then you need to output it too.


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    [php]
    <?php
    include_once 'dbconnect.inc.php';
    include_once 'header.html';
    include_once 'menu.html';

    echo '</br><table>
    <div="main">
    <tr><td> <div id="projectdiv">'.selectProjectBox().'</div> </td></tr>
    <tr><td> <div id="subsystemdiv"></div> </td></tr>
    <tr><td> <div id="productdiv"></div> </td></tr>
    <tr><td> <div id="tablediv"></div> </td></tr>
    </div>
    </table>
    ';

    function selectProjectBox()
    {
    $query = "SELECT project FROM trs GROUP BY project";

    echo "project:";

    echo "<select id=\"project\" name=\"project\" onchange=\"showSubsystem(this.value);\">\n<option selected=\"Selected\" value=\"\">-</option>\n";

    $result = mysql_query($query) or die ( mysql_error() );

    while( $row = mysql_fetch_array($result) )
    {
    $selectOption = $row;
    $html.="<option id=\"$selectOption\">$selectOption</option>\n";
    }

    $html.="</select>\n";
    echo $html;

    }
    ?>
    [/php]


    and the javascript, linked in from header.html.

    [php]
    var xmlHttp;

    //fuction to return the xml http object
    function getXMLHTTP()
    {
    var xmlhttp=false;

    //if the browser is mozilla/safari/opera
    if(window.XMLHttpRequest)
    {
    xmlhttp = new XMLHttpRequest();
    }
    //or internet explorer
    else if(window.ActiveXObject)
    {
    try
    {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
    try
    {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e)
    {
    xmlhttp = false;
    }
    }
    }
    return xmlhttp;
    }


    //calls findSubsystem.php to populate a drop down box
    //that shows only subsystems based on a particular project
    function showSubsystem(project)
    {
    var strURL="findSubsystem.php?project="+project;
    //var req = getXMLHTTP();
    xmlHttp = getXMLHTTP();

    if (xmlHttp)
    {
    xmlHttp.onreadystatechange = function()
    {
    if (xmlHttp.readyState == 4)
    {
    // only if "OK"
    if (xmlHttp.status == 200)
    {
    document.getElementById('subsystemdiv').innerHTML=xmlHttp.responseText;
    }
    else
    {
    alert("There was a problem while using XMLHTTP:\n" + xmlHttp.statusText);
    }
    }
    }
    xmlHttp.open("GET", strURL, true);
    xmlHttp.send(null);
    }
    }

    //calls findProduct.php to populate a drop down box
    //that shows only products based on a particular project and subsystem.
    function showProduct(subsystem)
    {
    var project = document.getElementById("project").value;

    var strURL="findProduct.php?project="+project+"&subsystem="+subsystem;
    var xmlHttp = getXMLHTTP();

    if (xmlHttp)
    {
    xmlHttp.onreadystatechange = function()
    {
    if (xmlHttp.readyState == 4)
    {
    // only if "OK"
    if (xmlHttp.status == 200)
    {
    document.getElementById('productdiv').innerHTML=xmlHttp.responseText;
    }
    else
    {
    alert("There was a problem while using XMLHTTP:\n" + xmlHttp.statusText);
    }
    }
    }
    xmlHttp.open("GET", strURL, true);
    xmlHttp.send(null);
    }
    }

    function showTable()
    {
    var project = document.getElementById("project").value;
    var subsystem = document.getElementById("subsystem").value;
    var product = document.getElementById("product").value;

    var strURL="showTable.php?project="+project+"&subsystem="+subsystem+"&product="+product;
    var xmlHttp = getXMLHTTP();

    if (xmlHttp)
    {
    xmlHttp.onreadystatechange = function()
    {
    if (xmlHttp.readyState == 4)
    {
    // only if "OK"
    if (xmlHttp.status == 200)
    {
    document.getElementById('tablediv').innerHTML=xmlHttp.responseText;
    }
    else
    {
    alert("There was a problem while using XMLHTTP:\n" + xmlHttp.statusText);
    }
    }
    }
    xmlHttp.open("GET", strURL, true);
    xmlHttp.send(null);
    }

    }
    [/php]

    also just to add, the javascript actually calls findsubsystem.php because there is a select box in that script that is meant to be populated but only a box and one option gets created <option>-</option>


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Cremo - check my post above the one with your code - you are not giving your options a value

    I'll just outline the way I might have done this which may not appeal to everyone but it's just another approach. Once you understand how all that ajax stuff works then start using a library. The big names are jquery, prototype, yahoo etc. but I am perhaps a bit unecessarily concerned about how large some script files will be especially if you are only making use of them here and there. For ajax I use fleegix. This is a matter of choice pure and simple but it's lightweight and created by a guy I respect in the javascript world Matthew Eernisse.

    I always develop a page that works without script. This is not always necessary especially if it's an internal intranet based site etc. but it's not that huge an effort to go to. With 3 dropdowns I would display all 3 select boxes on the page, the first with all of it's options and the next two empty and disabled. Beside the first dropdown a submit button saying something like "Refresh Options" which the user can click whenever they make a change. Rudimentary but will work for anyone with script turned off.

    For the ajax version I would still display all 3 selects (and hide the button) with the second and third disabled until they have options. All script would go into the external file. Using the well known addLoadEvent to setup the page once the page has loaded.

    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
    window.onload = func;
    } else {
    window.onload = function() {
    if (oldonload) oldonload();
    func();
    }
    }

    addLoadEvent(initPage);

    function initPage() {
    //assuming the selects are called project, subsystem and product
    var projsel = document.getElementById("project");
    var subsel = document.getElementById("subsystem");
    var prodsel = document.getElementById("product");
    if (projsel) projsel.onchange = getChildOptions;
    if (subsel) subsel.onchange = getChildOptions;
    if (prodsel) prodsel.onchange = getChildOptions;

    }

    For the actual ajax I find it best to use the same backend page, for example getchildoptions.php and pass it an ajaxid for example that will inidicate what results I am looking for. The php page can check this id and return what is expected based on that. I would almost always use an ajax post if possible and finally I would prefer not to return actual html instead passing back a simple delimited string when I just want to create option elements.

    If the options only need one value then it could be comma delimitted - option1,option2,option3 etc. or if an id is also needed then 1|options1,2|option2,3|option3. That makes it easy enough to parse.

    In this particular situation I would also include the id of the select that started this request in the response along with the child select as I am using a handler function that will be ignorant of which select made the request. Obviously you could use 3 seperate functions for each select and three seperate handlers but why make your code longer. So the response might be project,subsystem,option1,option2,option3 etc.

    function getChildOptions() {
    var selectedID = this.options[this.selectedIndex].value;
    var thisID = this.id;
    if (thisID === 'project') {
    fleegix.xhr.doPost(handle_getChildOptions, 'getchildoptions.php', 'ajaxid=1&selectedID=' + selectedID);
    } else if (thisID === 'subsystem') {
    fleegix.xhr.doPost(handle_getChildOptions, 'getchildoptions.php', 'ajaxid=2&selectedID=' + selectedID);
    } else if (thisID === 'product') {
    fleegix.xhr.doPost(handle_getChildOptions, 'getchildoptions.php', 'ajaxid=3&selectedID=' + selectedID);
    }
    }

    function handle_getChildOptions(resp, id) {
    var aropts = resp.split(',');
    var objcaller = document.getElementById(aropts[0]);
    var objchild = document.getElementById(aropts[1]);
    objchild.options.length = 0; //clears the child select's options
    var i = 0;
    for (i=2;i< aropts.length;i++) {
    objchild.options[objchild.options.length] = new Option(aropts, aropts);
    }
    }

    I can't cover all the ground here but I'm hoping it might give you some ideas. One final good practice is to disable the selects while making your ajax call and re-enable them when it is complete. Otherwise you would have to monitor ajax calls and cancel them when the user trys to make a change during a call which might be tricky.


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    only saw you edit now Musician. can we delete like the last 5 posts here so i don't look like a noob :o

    i'm going to look into using libraries when i get a bit more advanced in AJAX.


  • Advertisement
  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Cremo wrote: »
    only saw you edit now Musician. can we delete like the last 5 posts here so i don't look like a noob :o

    i'm going to look into using libraries when i get a bit more advanced in AJAX.

    I don't see any posts in this thread at all :)
    You are right though. Get to know Ajax and the DOM before making use of libraries.


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    This is a nice little book that is worth looking at:

    AJAX and PHP: Building Responsive Web Applications
    http://www.amazon.co.uk/AJAX-PHP-Building-Responsive-Applications/dp/1904811825/ref=sr_1_11?ie=UTF8&s=books&qid=1210161493&sr=8-11


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    I would strongly recommend that anyone who wants to learn javascript/ajax learn it independently from php/.net/ror etc. Also try and learn from the new breed of scripters out there advocating unobtrusive scripting. I don't know how the book webmonkey recommends approaches javascript but the simple test for me is that if it has something like <a href="#" onclick="javascript:...." in it then I don't want to know.

    I just finished Simply Javascript which is an excellent book and a great primer for writing good javascript.


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    musician wrote: »
    I would strongly recommend that anyone who wants to learn javascript/ajax learn it independently from php/.net/ror etc. Also try and learn from the new breed of scripters out there advocating unobtrusive scripting. I don't know how the book webmonkey recommends approaches javascript but the simple test for me is that if it has something like <a href="#" onclick="javascript:...." in it then I don't want to know.

    I just finished Simply Javascript which is an excellent book and a great primer for writing good javascript.
    Well the PHP is kept separate as it the server side code that the request goes to. This can easily be any server side language. The book mainly deals with the javascript/dom side of things (at least in the first half of the book).
    It goes into using PHP then to make it a bit more interactive but as I say its quite simple to use what ever language you comfortable with first.

    Getting a good understanding of the DOM object is quite essential and to be honest its easy since most of the methods you could almost guess.


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Webmonkey wrote: »
    Well the PHP is kept separate as it the server side code that the request goes to. This can easily be any server side language. The book mainly deals with the javascript/dom side of things (at least in the first half of the book).
    It goes into using PHP then to make it a bit more interactive but as I say its quite simple to use what ever language you comfortable with first.

    Getting a good understanding of the DOM object is quite essential and to be honest its easy since most of the methods you could almost guess.

    I would hope the php was kept seperate :) I'm sure it's an excellent book I just wouldn't want someone looking for a php/ajax book because they were a php developer instead of the best "ajax" book. I'm a .net developer and I wouldn't be too bothered looking for an asp.net/ajax book for various reasons but mainly because there are authors out there writing about cutting edge scripting most of whom don't fixate on one kind of server language and despite what people think it's not a good idea to learn the old way then check out the new way. Start with the new way and it's no more difficult.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    ok guys, i'm back again :o

    i have these boxes updating with the ajax calls perfectly now (and have for sometime) but what i want to be able to do is to have a submit button that the user can submit at anytime.

    ie. they select a project and they can hit submit and the value gets passed to another php script of mine eg test.php.

    or ie. again they select a project and subsystem and they hit submit the two values of the boxes get passed to the test.php script

    i have test looking like this at the moment...

    [php]
    <?php
    print_r($_GET);
    ?>
    [/php]and the form looks like this.

    [php]
    echo '</br><table>
    <form action="test.php" method="get">
    <div="main">
    <tr><td> <div id="projectdiv">'.selectProjectBox().'</div> </td></tr>
    <tr><td> <div id="subsystemdiv"></div> </td></tr>
    <tr><td> <div id="productdiv"></div> </td></tr>
    <tr><td> <div id="tablediv"></div> </td></tr>
    </div>
    </table>
    </form>
    ';
    [/php]now when i print out $_GET in test.php i get an empty array, but if i have <input type="hidden" name="test" value="test" /> inside the form it gets printed out in test.php.

    i'm guessing with AJAX code of the select boxes isn't sent and stored on the client. is there any way for me to get these values to be submitted to test.php?


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Cremo wrote: »
    i'm guessing with AJAX code of the select boxes isn't sent and stored on the client. is there any way for me to get these values to be submitted to test.php?

    It's no different to what you have been doing with the selects. You send the info using either an Ajax GET or POST to the php page.


  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    aye i just noticed that :o i actually had the <form ....> tag in the wrong place in the acutal code d'oh.


Advertisement