Page 1 of 1

Split -- Dynamic/Chained Selects using Ajax Prototype/JQuery

Posted: Fri Aug 31, 2007 11:13 am
by CoderGoblin
Split from Coding Critque topic Dynamic/Chained Selects using Ajax Prototype/JQuery.
davidtube wrote:This has been very useful for me. Thank you.

I have a bit of a problem though. I've changed the code so the listboxes are populated from a database, and it seems to work but I have an error message when the page first loads. After selecting an option the error message vanishes. The error message I get is "Warning: Invalid argument supplied for foreach()

You can see how the code works here and which parts I've changed. Does anyone know what's wrong with the foreach loop?

Code: Select all

$otherslist=mysql_query("SELECT subcat FROM subcat WHERE catagory='Others' ORDER BY subcat");
while ($row = mysql_fetch_assoc($otherslist)) {
   $others[] = $row['subcat'];
}

$sublist=array('Games'=>$games,
               'Electronics'=>$electronics,
               'DVDs'=>$dvd,
               'Music'=>$music,
               'Others'=>$others);



// Here to the end of the code remains as in the original example


$value=1;
if (!empty($_POST['first'])) {
    if (isset($sublist[$_POST['first']])) $value=$_POST['first'];
}
$name_list='';


// The error message I get is "Warning: Invalid argument supplied for foreach()"


foreach ($sublist[$value] as $name) {
    $name_list.="<option value="{$name}">{$name}</option>\n";
}
echo '<select name="second">'.$name_list.'</select>';
?>
Pleased the code was useful...

The answer is, luckily for me :wink:, quite simple I think... If you look at the "foreach" in question it is using $sublist[$value]. $value is set to 1 by default before being potentially overwritten by any $_POST value. Therefore you should change the default $value to be an allowed one.. 'Games','Electronics','DVDs','Music' or 'Others' rather than 1.


Note... Please note my previous request that questions of the nature "can't get my modified code to work..." should be split off from the original topic. This is to avoid confusing others trying to get to grips with the original code.

Posted: Fri Aug 31, 2007 11:44 am
by davidtube
Sorry about posting that. I had read what you said earlier in the day about posting that sort of question but just forgot.

Thanks very much for taking the time to work out the problem and start a new thread.

Posted: Fri Aug 31, 2007 1:54 pm
by CoderGoblin
No problem... Did it work though ?