pwalters09
01-12-2010, 03:54 PM
Hi guys
I am having a little trouble, I need a form that automatically updates when another dropdown box option is selected
For example:
I have a menu item with a list of categories, a user clicks on the movies category and the subcategory list automatically populates with the subcategories for movies
Or:
A user clicks on the software category, and the subcategory list automatically populates with the subcategories for software
And so on...
The categorys and subcategories are in a database, for example the main category for movies is ID number 10003, and the code i use in the subcategories dropdown for that specific main category is
echo "<select name='subcat'>";
$subcat1 = mysql_query("SELECT * FROM subcats WHERE maincat = '10003'") or die("MySQL ran away.");
while($subcat2 = mysql_fetch_assoc($subcat1))
{
echo "<option value='".$subcat2['subcat']."'>".$subcat2['subcat']."</option>";
}
echo "</select>";
That code simply fetches the subcategorys for the specific main category, of course i have lots of categorys which are fetched from the database, but i want to be able to automatically update the subcategory dropdown with the correct subcategories only for the main category. A perfect example would be demonoid.com's torrent search feature
Thanks...
mattle
01-12-2010, 05:26 PM
There are two basic ways to accomplish this:
The old-school way:
Set up an onChange() event when the main category runs that reloads the page with a GET URI (http:...php?main_cat=10003)
Then in your PHP script if $_GET['main_cat'] is set, you draw the second select box with just the right options.
The new-school way:
Set up an onChange() event that fires an AJAX routine. This routine passes (probably via GET) the main category to a short PHP script. The return value of that PHP script is then put between the beginning and end select tags for your subcategory.
The short PHP script simply reads the main category id and echoes the appropriate option list.
There's a whole ton of tutorials on both of these approaches that are just a google away ;)
pwalters09
01-12-2010, 07:12 PM
OK lol sorry for the hassle, after a little twidling with my script i managed to get this far,
<?
//
// - Theme And Language Updated 25.Nov.05
//
ob_start("ob_gzhandler");
require_once("backend/functions.php");
dbconn(false);
loggedinorreturn();
if ($RATIO_WARNINGON && $CURUSER)
{
include("ratiowarn.php");
}
$searchstr = unesc($_GET["search"]);
$cleansearchstr = searchfield($searchstr);
if (empty($cleansearchstr))
unset($cleansearchstr);
///////////////////////////MOD FOR SORTING///////////////////////////////////
if ($_GET['sort'] && $_GET['type']) {
$column = '';
$ascdesc = '';
switch($_GET['sort']) {
case '1': $column = "name"; break;
case '2': $column = "nfo"; break;
case '3': $column = "Comments"; break;
case '4': $column = "size"; break;
case '5': $column = "times_completed"; break;
case '6': $column = "seeders"; break;
case '7': $column = "leechers"; break;
case '8': $column = "category"; break;
default: $column = "id"; break;
}
switch($_GET['type']) {
case 'asc': $ascdesc = "ASC"; break;
case 'desc': $ascdesc = "DESC"; break;
default: $ascdesc = "DESC"; break;
}
$orderby = "ORDER BY torrents." . $column . " " . $ascdesc;
$pagerlink = "sort=" . $_GET['sort'] . "&type=" . $_GET['type'] . "&subcat=" . $_GET['type'] . "&";
} else {
$pagerlink = "";
$orderby = "ORDER BY torrents.id DESC";
}
////////////////////////END SORTING MOD/////////////////////////////////
//$orderby = "ORDER BY torrents.id DESC"; //REMOVE FOR SORT MOD
$addparam = "";
$wherea = array();
if ($_GET["incldead"] == 1) {
$addparam .= "incldead=1&";
if (!isset($CURUSER) || get_user_class < UC_ADMINISTRATOR)
$wherea[] = "banned != 'yes'";
}
else
if ($_GET["incldead"] == 2)
$wherea[] = "visible = 'no'";
else
$wherea[] = "visible = 'yes'";
if ($_GET["cat"]) {
$wherea[] = "category = " . sqlesc($_GET["cat"]);
$addparam .= "category=" . urlencode($_GET["cat"]) . "&";
}
if ($_GET["subcat"]) {
$wherea[] = "subcat = " . sqlesc($_GET["cat"]);
$addparam .= "subcat=" . urlencode($_GET["cat"]) . "&";
}
$wherebase = $wherea;
if (isset($cleansearchstr)) {
$wherea[] = "MATCH (search_text, ori_descr) AGAINST (" . sqlesc($searchstr) . ")";
$addparam .= "search=" . urlencode($searchstr) . "&";
//$orderby = ""; //REMOVE FOR SORT MOD
}
$where = implode(" AND ", $wherea);
if ($where != "")
$where = "WHERE $where";
$res = mysql_query("SELECT COUNT(*) FROM torrents $where")
or die(mysql_error());
$row = mysql_fetch_array($res);
$count = $row[0];
if (!$count && isset($cleansearchstr)) {
$wherea = $wherebase;
//$orderby = "ORDER BY id DESC"; //REMOVE FOR SORT MOD
$searcha = explode(" ", $cleansearchstr);
$sc = 0;
foreach ($searcha as $searchss) {
if (strlen($searchss) <= 1)
continue;
$sc++;
if ($sc > 5)
break;
$ssa = array();
foreach (array("search_text", "ori_descr") as $sss)
$ssa[] = "$sss LIKE '%" . sqlwildcardesc($searchss) . "%'";
$wherea[] = "(" . implode(" OR ", $ssa) . ")";
}
if ($sc) {
$where = implode(" AND ", $wherea);
if ($where != "")
$where = "WHERE $where";
$res = mysql_query("SELECT COUNT(*) FROM torrents $where");
$row = mysql_fetch_array($res);
$count = $row[0];
}
}
if ($count) {
//////////////////////////////////SORT MOD///////////////////////////////////////
if ($addparam != "") {
if ($pagerlink != "") {
if ($addparam{strlen($addparam)-1} != ";") { // & = &
$addparam = $addparam . "&" . $pagerlink;
} else {
$addparam = $addparam . $pagerlink;
}
}
} else {
$addparam = $pagerlink;
}
//////////////////////////////////////END SORT MOD////////////////////////////////
list($pagertop, $pagerbottom, $limit) = pager(10, $count, "torrents-search.php?$addparam");
$query = "SELECT torrents.id, torrents.category, torrents.subcat, torrents.leechers, torrents.nfo, torrents.seeders, torrents.name, torrents.times_completed, torrents.size, torrents.added, torrents.comments,torrents.numfiles,torrents.filename,torrents.owner,IF(torrents.nfo <> '', 1, 0) as nfoav," .
"IF(torrents.numratings < $minvotes, NULL, ROUND(torrents.ratingsum / torrents.numratings, 1)) AS rating, categories.name AS cat_name, categories.image AS cat_pic, users.username, users.privacy FROM torrents LEFT JOIN categories ON category = categories.id LEFT JOIN users ON torrents.owner = users.id $where $orderby $limit";
$res = mysql_query($query)
or die(mysql_error());
}
else
unset($res);
if (isset($cleansearchstr))
stdhead("Search results for \"$searchstr\"");
else
stdhead("Browse Torrents");
$cats = genrelist();
$catdropdown = "";
foreach ($cats as $cat) {
$catdropdown .= "<option value=\"" . $cat["id"] . "\"";
if ($cat["id"] == $_GET["cat"])
$catdropdown .= " selected=\"selected\"";
$catdropdown .= ">" . htmlspecialchars($cat["name"]) . "</option>\n";
}
begin_frame("" . SEARCH_TITLE . "",center);
?><CENTER>
<form name="frmSelect" method="get" action="torrents-search.php"><br />
<? print("" . SEARCH . "\n"); ?>
<input type="text" name="search" size="40" value="<?= htmlspecialchars($searchstr) ?>" />
<? print("" . IN . "\n"); ?>
<style tyle=text/css>
option.red {background-color: #cc0000; font-weight: bold; font-size: 12px; color: white;}
option.green {background-color: green; font-size: 12px; color: white;}
</style>
<script src="request.js"></script>
<script>
function handleOnChange(dd1)
{
var idx = dd1.selectedIndex;
var val = dd1[idx].text;
var par = document.forms["frmSelect"];
var parelmts = par.elements;
var subcatsel = parelmts["subcat"];
var cat = val;
if (cat != "Select Main Category")
{
Http.get({
url: "./subcats_" + cat + ".php",
callback: fillsubcat,
cache: Http.Cache.Get
}, [subcatsel]);
}
}
function fillsubcat(xmlreply, subcatelmt)
{
if (xmlreply.status == Http.Status.OK)
{
var subcatresponse = xmlreply.responseText;
var subcatar = subcatresponse.split("|");
subcatelmt.length = 1;
subcatelmt.length = subcatar.length;
for (o=1; o < subcatar.length; o++)
{
subcatelmt[o].text = subcatar[o];
}
}
else
{
alert("Cannot handle the AJAX call.");
}
}
</script>
<select name="cat" onChange="handleOnChange(this);">
<option>Select Main Category</option>
<?
$cats = genrelist();
$catdropdown = "";
foreach ($cats as $cat) {
$subcat1 = mysql_query("SELECT * FROM categories WHERE id = '".$cat["id"]."'") or die(mysql_error());
$catdropdown .= "<option value=\"" . $cat["id"] . "\"";
if ($cat["id"] == $_GET["cat"])
$catdropdown .= " selected=\"selected\"";
$catdropdown .= ">" . htmlspecialchars($cat["name"]) . "</option>";
}
$deadchkbox = "<input type=\"checkbox\" name=\"incldead\" value=\"1\"";
if ($_GET["incldead"])
$deadchkbox .= " checked=\"checked\"";
$deadchkbox .= " /> " . INC_DEAD . "\n";
?>
<?= $catdropdown ?>
</select> <select name="subcat"><option>Select A Subcategory</option></select>
<?= $deadchkbox ?>
<input type="submit" value="<? print("" . SEARCH . "\n"); ?>" />
</form><br><hr><br>
<? print("" . SHOW_ALL . "\n"); ?>
<form method="get" action="torrents-search.php">
<select name="cat">
<option value="0">(Any type)</option>
<?= $catdropdown ?>
</select>
<? /* = $deadchkbox */ ?>
<select name=incldead>
<option value="0">Active</option>
<option value="1">Including dead</option>
<option value="2">Only dead</option>
</select>
<input type="submit" class=btn value="<? print("" . DISPLAY . "\n"); ?>" style="margin-left: 10px"/>
</form>
</CENTER>
<?
if ($count) {
end_frame();
echo "<br /><br />\n";
begin_frame("" . SEARCH_RESULTS . "");
print($pagertop);
torrenttable($res);
print($pagerbottom);
}
else {
if (isset($cleansearchstr)) {
bark2("" . NOTHING_FOUND . "", "" . NO_UPLOADS . "");
}
else {
bark2("" . NOTHING_FOUND . "", "" . NO_RESULTS . "");
}
}
end_frame();
stdfoot();
?>
</body>
</html>
And here is an example of one of the PHP files I call to get the list of subcategories
<?php
require 'backend/functions.php';
require 'backend/config.php';
dbconn();
$sql = mysql_query("SELECT * FROM subcats WHERE maincat = '10012'") or die(mysql_error());
while($row = mysql_fetch_assoc($sql))
{
$subcatid = $row['id'];
echo "|" . $row['subcat'] . "";
}
?>
Now the search form will update the forms as I wanted it to, and auto populates the second dropdown, now my question is how can I set an option value, see my database goes by ID numbers for the subcategories, but when I search it comes up with the main subcategory name, i need it to display the ID in the option which is passed to the server, but i need the users to see the subcat name, at the minute it looks like this:
<option>SOME SUB CATEGORY NAME</option>
But I need it like this:
<option value='xxx'>SOME SUB CATEGORY NAME</option>
Any help doing this?
Thanks again
mattle
01-13-2010, 09:26 AM
Sorry...I don't have the time to look through all that code you posted. Generally, when posting code, you should post the minimum amount of code necessary to replicate the behavior you're experiencing. Also, please use the [PHP] tags to take advantage of syntax highlighting and preserve your indentation...makes it a lot easier for us to get an idea of what's going on at a glance.
pwalters09
01-13-2010, 09:40 AM
its not a problem mate i just wrote a little script to select the id of the subcategory based on the main category and sub category name :)
Thanks anyways