populating <select> elements using php & javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
linksdemon
Forum Newbie
Posts: 1
Joined: Fri May 15, 2009 4:40 am

populating <select> elements using php & javascript

Post by linksdemon »

Dear Folks

I have a problem that involves php and javascript which i hope someone can find the time to help me with.
I have a php page with two drop-down select elements used for filtering a list of objects underneath. The first selector is the top-level filter with the options of "Show All", "Option 1", "Option 2", "Option 3". If top-level "Show All" is left as the default and the "Filter List" button is clicked, then the php retrieves all the mysql objects and displays them in the list.
If any of the other top-level filter options are selected then the sub-filter options are supposed to present more filter options depending on which top-level filter option was selected. For eg. if top-level option 1 is selected, then the sub-filter options could be A, B, C & D. If top-level option 2 is selected, the sub-filter options could be E, F, G & H. You get the idea. The problem is, i want the sub-filter options to be recalculated on the client-side using javascript so as to avoid interrogating the database each time a selection is made from the top-level filter.
What i want to do is make just one server-side database call using php to get all the possible top-level and sub-level filter options so as to cut down network traffic and speed up the web app.
In order to do this, i have an "onload" event in the <body> section of the php page in question which calls a javascript function that is supposed to initialize the top-level filter with values. When a selection is made from the top-level filter, this triggers an "onchange" event which is wired to a javascript function that repopulates the sub-filter options.
The values come from a 2-d javascript array which is populated via a php call to get the values from the database.
The array has the following structure:
level1element[name, value, level2element]
The "name" corresponds to the label attribute of the <option> element; the "value" corresponds to the value attribute of the <option> element and the level2element is an array with the following structure:
level2element[name, value]
where the meaning of the "name" and "value" elements are the same.
When the page is loaded, the following php gets run:

Code: Select all

 
<?php
    $query = "SELECT * FROM pagecategories ORDER BY level, categoryid;";
    $results1 = mysql_query($query);
    $i = 0;
    while ($row1 = mysql_fetch_array($results1))
    {
        if ($row1['level'] == 1)
        {
            $categoryLevel1Name = $row1['categoryname'];
            $categoryLevel1Value = $row1['categoryid'];
            // create level 2 page categories
            echo("level2Array = new Array();");
            $results2 = mysql_query($query);
            $j = 0;
            // initialize level 2 array with default value
            echo("level2array[".$j++."] = createLevel2Element(".DEFAULT_FILTER_NAME.", ".DEFAULT_FILTER_VALUE.");");
            while ($row2 = mysql_fetch_array($results2))
            {
                if ($row2['level'] == 2 && $row2['parentid'] == $categoryLevel1Value)
                {
                    echo("level2array[".$j++."] = createLevel2Element(".$row2['categoryname'].", ".$row2['categoryid'].");");
                }
            }
            // initialize level 1 array with default value
            echo("level1array[".$i++."] = createLevel1Element(".DEFAULT_FILTER_NAME.", ".DEFAULT_FILTER_VALUE.", level2array);");
            // check if the level 2 array has any elements; if it does, create the level 1 array element
            echo("if (level2array.length != 0)");
            echo("{");
            echo("level1array[".$i++."] = createLevel1Element(".$categoryLevel1Name.", ".$categoryLevel1Value.", level2array);");
            echo("}");
        }
    }
?>
As you can see, there are php echo statements which make calls to javascript functions that load the 2-d array. I can see that the array has been loaded okay when i do a "View Source" on the page. The above php and associated javascript functions are all enclosed in <script> tags located in the <body> tags of the php page in question.
The problem is the following: i can't work out how to use javascript to populate the <option> elements, either for the top-level filter, or the sub-filter. At the moment nothing shows in either drop-down select list.
Will be happy to read helpful suggestions from anyone who knows more about it than me!
Cheers,

linksdemon
Last edited by Benjamin on Fri May 15, 2009 8:33 am, edited 1 time in total.
Reason: Added [code=php] tags.
nyoka
Forum Commoner
Posts: 45
Joined: Thu Apr 09, 2009 12:53 pm

Re: populating <select> elements using php & javascript

Post by nyoka »

Personally I favour jquery for dom manipulation, here is a file that shows one way of doing what you want. The example passes a php array containing the data you have into javascript using json. The select boxes change without reloading the page.
Note:
posted data for each select will be an integer starting from 0.
you will need to download jquery at http://jquery.com

Code: Select all

 
<?php
/*
this is where you get your data
and output it in a form that javascript
can understand for processing
*/
$array = array(
    'topLevel' => array(
        array('name' => 'Show All', 'values' => array('a', 'b', 'c', 'd', 'e')),
        array('name' => 'Option 1', 'values' => array('a', 'c', 'e')),
        array('name' => 'Option 2', 'values' => array('b', 'd')),
        array('name' => 'Option 3', 'values' => array('e'))
    )
);
?>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
var dataArray = <?= json_encode($array) ?>;
$(document).ready(function(){
    // setup first select
    var h = '';
    $('select[name=topLevel]').html('');
    for (var i = 0; i < dataArray.topLevel.length; i++) {
        h += '<option value="'+i+'">'+dataArray.topLevel[i].name+'</option>';
    }
    $('select[name=topLevel]').html(h);
    // setup next select
    resetNextLevel();
});
// resets next level based on first
function resetNextLevel() {
    var h = '';
    var tLevel = $('select[name=topLevel]').val();
    $('select[name=nextLevel]').html('');
    for (var i = 0; i < dataArray.topLevel[tLevel].values.length; i++) {
        h += '<option value="'+i+'">'+dataArray.topLevel[tLevel].values[i]+'</option>';
    }
    $('select[name=nextLevel]').html(h);
}
</script>
</head>
<body>
 
<select name="topLevel" onchange="resetNextLevel()"></select>
&nbsp;&nbsp;
<select name="nextLevel" onchange="resetNextLevel()"></select>
 
</body>
</html>
 
Last edited by Benjamin on Fri May 15, 2009 10:41 pm, edited 1 time in total.
Reason: Fixed code tags.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: populating <select> elements using php & javascript

Post by josh »

If you're going to aggressively load it just serialize the object graph to JSON and output it in your source code.
Post Reply