Jump to content

Recommended Posts

hi..i hope someone could shed me some of their wisdom on this..

ok,so here's my dilemma..

i have 3 dropdowns. first is for the category,second is for the subcategory,and last is for the subcategory of the second subcategory..

it works fine but my problem is,the whole page reloads every time i choose a category and subcategory. i just want the comboboxes to reload,not the whole page..i've researched some other related topics but i'm not sure where to put the code..here's what i've been doing>>

*****

database:

CREATE TABLE category ( cat_id int(2) NOT NULL auto_increment, category varchar(25) NOT NULL default '', PRIMARY KEY (cat_id) ) TYPE=MyISAM; 
# # Dumping data for table `category` # 
INSERT INTO category VALUES (1, 'Fruits'); INSERT INTO category VALUES (2, 'Colors'); INSERT INTO category VALUES (3, 'Games'); INSERT INTO category VALUES (4, 'Vehicles'); 
# -------------------------------------------------------- # # Table structure for table `subcategory` # 
CREATE TABLE subcategory ( subcat_id int(3) NOT NULL auto_increment, cat_id int(2) NOT NULL default '0', subcategory varchar(25) NOT NULL default '', UNIQUE KEY subcat_id (subcat_id) ) TYPE=MyISAM;
# # Dumping data for table `subcategory` # 
INSERT INTO subcategory VALUES (1, 1, 'Mango'); INSERT INTO subcategory VALUES (2, 1, 'Banana'); INSERT INTO subcategory VALUES (3, 1, 'Orange'); INSERT INTO subcategory VALUES (4, 1, 'Apple'); INSERT INTO subcategory VALUES (5, 2, 'Red'); INSERT INTO subcategory VALUES (6, 2, 'Blue'); INSERT INTO subcategory VALUES (7, 2, 'Green'); INSERT INTO subcategory VALUES (8, 2, 'Yellow'); INSERT INTO subcategory VALUES (9, 3, 'Cricket'); INSERT INTO subcategory VALUES (10, 3, 'Football'); INSERT INTO subcategory VALUES (11, 3, 'Baseball'); INSERT INTO subcategory VALUES (12, 3, 'Tennis'); INSERT INTO subcategory VALUES (13, 4, 'Cars'); INSERT INTO subcategory VALUES (14, 4, 'Trucks'); INSERT INTO subcategory VALUES (15, 4, 'Blkes'); INSERT INTO subcategory VALUES (16, 4, 'Train');
# -------------------------------------------------------- # # Table structure for table `subcategory2` # 
CREATE TABLE subcategory2 ( subcat_id int(3) NOT NULL default '0', subcat2 varchar(15) NOT NULL default '' ) TYPE=MyISAM; 
# # Dumping data for table `subcategory2` # 
INSERT INTO subcategory2 VALUES (1, 'Mango good'); INSERT INTO subcategory2 VALUES (1, 'Mango bad'); INSERT INTO subcategory2 VALUES (2, 'Banana sweet'); INSERT INTO subcategory2 VALUES (2, 'Banana hot'); INSERT INTO subcategory2 VALUES (3, 'Orange sweet'); INSERT INTO subcategory2 VALUES (3, 'Orange Sour'); INSERT INTO subcategory2 VALUES (4, 'Apple sweet'); INSERT INTO subcategory2 VALUES (4, 'Apple sour'); INSERT INTO subcategory2 VALUES (5, 'Red light'); INSERT INTO subcategory2 VALUES (5, 'Red Zone'); INSERT INTO subcategory2 VALUES (6, 'Blue deep'); INSERT INTO subcategory2 VALUES (6, 'Blue light'); INSERT INTO subcategory2 VALUES (7, 'Green light'); INSERT INTO subcategory2 VALUES (7, 'Green color'); INSERT INTO subcategory2 VALUES (9, 'Cricket Oneday'); INSERT INTO subcategory2 VALUES (9, 'Cricket test'); INSERT INTO subcategory2 VALUES (10, 'Football world'); INSERT INTO subcategory2 VALUES (10, 'Football team'); INSERT INTO subcategory2 VALUES (11, 'Base Ball team'); INSERT INTO subcategory2 VALUES (11, 'Base ball game'); INSERT INTO subcategory2 VALUES (13, 'Cars Big'); INSERT INTO subcategory2 VALUES (13, 'Cars small'); INSERT INTO subcategory2 VALUES (14, 'Trucks Big'); INSERT INTO subcategory2 VALUES (14, 'Trucks small'); INSERT INTO subcategory2 VALUES (15, 'Bikes sports'); INSERT INTO subcategory2 VALUES (15, 'Bike small'); INSERT INTO subcategory2 VALUES (16, 'Train fast'); INSERT INTO subcategory2 VALUES (16, 'Train slow'); INSERT INTO subcategory2 VALUES (8, 'Yellow card'); INSERT INTO subcategory2 VALUES (8, 'Yellow line'); INSERT INTO subcategory2 VALUES (12, 'Tennis Long'); INSERT INTO subcategory2 VALUES (12, 'Tennis table'); 

*****

<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value; 
self.location='dd3.php?cat=' + val ;
}
function reload3(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value; 
var val2=form.subcat.options[form.subcat.options.selectedIndex].value; 
self.location='dd3.php?cat=' + val + '&cat3=' + val2 ;
}
</script>
</head>
<body>

<?php

///////// Getting the data from Mysql table for first list box//////////
$quer2=mysql_query("SELECT DISTINCT category,cat_id FROM category order by category"); 
///////////// End of query for first list box////////////

/////// for second drop down list,check if category is selected else will display all the subcategory///// 
//$cat=$HTTP_GET_VARS['cat']; // This line is added to take care if your global variable is off
@$cat=$_GET['cat'];
if(isset($cat) and strlen($cat) > 0){
$quer=@mysql_query("SELECT DISTINCT subcategory,subcat_id FROM subcategory where cat_id=$cat order by subcategory"); 
}
else
{
$quer=@mysql_query("SELECT DISTINCT subcategory,subcat_id FROM subcategory order by subcategory"); 
} 
////////// end of query for second subcategory drop down list box 

////////////////////////////////// for Third drop down list we will check if sub category is selected else we will display all the subcategory3///// 

//$cat3=$HTTP_GET_VARS['cat3']; // This line is added to take care if your global variable is off
@$cat3=$_GET['cat3'];
if(isset($cat3) and strlen($cat3) > 0){
$quer3=mysql_query("SELECT DISTINCT subcat2 FROM subcategory2 where subcat_id=$cat3 order by subcat2"); 
}else{$quer3=mysql_query("SELECT DISTINCT subcat2 FROM subcategory2 order by subcat2"); } 
////////// end of query for third subcategory drop down list box 
///////////////////////////

echo "<form method=post name=f1 action='dd3ck.php'>";

////////// Starting of first drop downlist /////////
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
while($noticia2 = mysql_fetch_array($quer2)) { 
if($noticia2['cat_id']==@$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
////////////////// This will end the first drop down list ///////////

////////// Starting of second drop downlist /////////
echo "<select name='subcat' onchange=\"reload3(this.form)\"><option value=''>Select one</option>";
while($noticia = mysql_fetch_array($quer)) { 
if($noticia['subcat_id']==@$cat3)
{
echo "<option selected value='$noticia[subcat_id]'>$noticia[subcategory]</option>"."<BR>";}
else
{
echo "<option value='$noticia[subcat_id]'>$noticia[subcategory]</option>";}
}
echo "</select>";
////////////////// This will end the second drop down list ///////////////////// Starting of third drop downlist /////////

echo "<select name='subcat3' ><option value=''>Select one</option>";
while($noticia = mysql_fetch_array($quer3)) { 
echo "<option value='$noticia[subcat2]'>$noticia[subcat2]</option>";
}
echo "</select>";
////////////////// This will end the third drop down list ///////////
echo "<input type=submit value='Submit the form data'></form>";
?>

</body>
</html> 

 

EDIT: CODE/PHP tags are wonderful aren't they?

 

 

Hi.

I have just done this myself a few days ago.

Try the site below - I have the code working perfectly.

 

http://roshanbh.com.np/2008/01/populate-triple-drop-down-list-change-options-value-from-database-using-ajax-and-php.html

 

This code uses hardcoded values for the first menu option which I've modified to use a mysql query instead. The only fault with the existing code is that if you change your selection on the first menu, the 3rd does not reset but I've also modified that to work too with the help of forum member radar.

 

If you need any help adapting this code for your needs give me a shout and I'll do my best to help out

hello again,

i've checked the link you gave me and tried out the code..

but unfortunately i don't know my way around ajax and i don't know where or how i'm going to start with it on my project...i'm still haivng trouble adapting to it after a couple of tryouts on mine..

Hiya.

I've got this working using the link I posted to you.

Here's the code to do it.

 

Change the hostname, username and password in the db_config file to match your database and it should work straight away.

It's not the complete code - there's no submit button etc - but the functionality works without reloading the whole page.

The start and end of each file is marked with ********************* just to make it easier to read on this page

Hope it helps you out.

 

 

Filename: db_config.php

*************************************************************************
<?php
$dbhost = 'hostname;
$dbuser = 'username';
$dbpass = 'password';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die                      ('Error connecting to mysql');

$dbname = $dbuser;
mysql_select_db($dbname);
?>
*************************************************************************

 

 

 

Filename: main.php

*************************************************************************
<html>
<head>

<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
// If you have any problem contact me at http://roshanbh.com.np

function getXMLHTTP() { //fuction to return the xml http object
	var xmlhttp=false;	
	try{
		xmlhttp=new XMLHttpRequest();
	}
	catch(e)	{		
		try{			
			xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e){
			try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e1){
				xmlhttp=false;
			}
		}
	}

	return xmlhttp;
    }

function get_subcat(catId) {		
	var strURL="findsubcat.php?catId="+catId;
	var req = getXMLHTTP();

	if (req) {

		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {						
					document.getElementById('subcat_div').innerHTML=req.responseText;						
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			

		req.open("GET", strURL, true);
		req.send(null);
	}		

}

function get_subcat2(subcatId) {		
	var strURL="findsubcat2.php?subcatId="+subcatId;
	var req = getXMLHTTP();

	if (req) {

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

}

</script>

</head>
<body>

<form method=post name=f1 action='dd3ck.php'>
<div id="first_drop_down">
<select name="catId" onChange="get_subcat(this.value);get_subcat2(0)">
<option>Select one</option>
<?php 
include ('db_connect.php');
$query=("SELECT DISTINCT cat_id, category FROM category order by category"); 
$result=mysql_query($query);
while($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['cat_id']?>><?php echo $row['category']?></option>
<? } ?>
</select>

<div id="subcat_div">
<?php include ('findsubcat.php'); ?>
</div>

<div id="subcat2_div">
<?php include ('findsubcat2.php'); ?>
</div>

</body>
</html> 
*************************************************************************

 

 

 

Filename: findsubcat.php

*************************************************************************
<!--//---------------------------------+
//  Developed by Roshan Bhattarai    |
//	http://roshanbh.com.np           |
//  Contact for custom scripts       |
//  or implementation help.          |
//  email-nepaliboy007@yahoo.com     |
//---------------------------------+-->
<?
#### Roshan's Ajax dropdown code with php
#### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
#### if you have any problem contact me at http://roshanbh.com.np
#### fell free to visit my blog http://roshanbh.com.np
?>

<? $catId=intval($_GET['catId']);

include ('db_connect.php');

if ($catId!=0)
{
$query="SELECT DISTINCT subcategory,subcat_id FROM subcategory where cat_id='$catId' order by subcategory";
$result=mysql_query($query);
}
else
{
$query="SELECT DISTINCT subcategory,subcat_id FROM subcategory order by subcategory";
$result=mysql_query($query);
}

?>
<select name="subcatId" onchange="get_subcat2(this.value)">

<option>Select one</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['subcat_id']?>><?=$row['subcategory']?></option>
<? } ?>

</select>
*************************************************************************

 

 

 

Filename: findsubcat2.php

*************************************************************************
<!--//---------------------------------+
//  Developed by Roshan Bhattarai    |
//	http://roshanbh.com.np           |
//  Contact for custom scripts       |
//  or implementation help.          |
//  email-nepaliboy007@yahoo.com     |
//---------------------------------+-->
<?
#### Roshan's Ajax dropdown code with php
#### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
#### if you have any problem contact me at http://roshanbh.com.np
#### fell free to visit my blog http://php-ajax-guru.blogspot.com
?>

<? 
$subcatId=intval($_GET['subcatId']);

include ('db_connect.php');

if ($subcatId!=0)
{
$query="SELECT DISTINCT subcat2 FROM subcategory2 where subcat_id='$subcatId' order by subcat2";
$result=mysql_query($query);
}
else
{
$query="SELECT DISTINCT subcat2 FROM subcategory2 order by subcat2";
$result=mysql_query($query);
}
?>
<select name="subcat2Id">

<option>Select one</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['subcat2']?>><?=$row['subcat2']?></option>
<? } ?>
</select>
*************************************************************************

  • 3 weeks later...

hello again!

thank you so much for your help,my program now runs smoothly.  ;D

but i've just made a few modifications on some parts like this one:

while($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['cat_id']?>><?php echo $row['category']?></option>
<? } ?>

the first menu changes but when i try to choose from the submenus all i get to view is this ">"..so i made some changes and it's now perfect. :D

thanks! ;D

  • 8 months later...

Hi. I've been trying to figure this out for sometime now. I have two issues with the code I have.

#1 - I need the page to not reload when each selection is made

#2 - I need the form to submit into a div instead of an iframe

 

I have tried what is posted, but I can't get it to work. I would really appreciate any help!

 

<?php
//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
//  Please don't  remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************

require "config.php"; // Your Database details 
?>

<!doctype html public "-//w3c//dtd html 3.2//en">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>Textbooks</title>
<meta name="GENERATOR" content="Arachnophilia 4.0" />
<meta name="FORMATTER" content="Arachnophilia 4.0" />

<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.TERM.options[form.TERM.options.selectedIndex].value; 
self.location='dd3.php?TERM=' + val ;
}
function reload3(form)
{
var val=form.TERM.options[form.TERM.options.selectedIndex].value; 

var val2=form.CURR.options[form.CURR.options.selectedIndex].value; 

self.location='dd3.php?TERM=' + val + '&CURR=' + val2 ;
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<script type="text/javascript">var GB_ROOT_DIR = "/greybox/";</script>
<script type="text/javascript" src="/greybox/AJS.js"></script>
<script type="text/javascript" src="/greybox/AJS_fx.js"></script>
<script type="text/javascript" src="/gb_scripts.js"></script>
<link href="/greybox/gb_styles.css" rel="stylesheet" type="text/css" />
</style>
</head>

<body id="page2" onload="new ElementMaxHeight();">

        <div class="col-1 maxheight" style="width: 253px; height: 718px">
           <h2><b><b>make your selection</b></b></h2>
            <div class="indent-1" style="width: 280px; height: 415px">
                        <h4 class="auto-style2">Textbook Information</h4><br />
	               <span class="auto-style4">Course information</span><br /><br />

	<?

$cat=$_POST['TERM'];
$subcat=$_POST['CURR'];
$subcat3=$_POST['COURSE'];

///////// Getting the data from Mysql table for first list box//////////
$quer2=mysql_query("SELECT DISTINCT TERM FROM SUMMER order by TERM"); 
///////////// End of query for first list box////////////

/////// for second drop down list we will check if category is selected else we will display all the subcategory///// 
@$cat=$_GET['TERM']; // This line is added to take care if your global variable is off
if(isset($cat) and strlen($cat) > 0){
$quer=mysql_query("SELECT DISTINCT CURR FROM SUMMER where TERM = '$cat' order by CURR"); 
}else{$quer=mysql_query("SELECT DISTINCT CURR FROM SUMMER order by CURR"); } 
////////// end of query for second subcategory drop down list box ///////////////////////////

/////// for Third drop down list we will check if sub category is selected else we will display all the subcategory3///// 
@$cat3=$_GET['CURR']; // This line is added to take care if your global variable is off
if(isset($cat3) and strlen($cat3) > 0){
$quer3=mysql_query("SELECT DISTINCT COURSE FROM SUMMER where TERM = '$cat' AND CURR = '$cat3' order by COURSE"); 
}else{$quer3=mysql_query("SELECT DISTINCT COURSE FROM SUMMER order by COURSE"); } 
////////// end of query for third subcategory drop down list box ///////////////////////////

echo "<form method=post name=f1 action='dd3ck.php' target='content'>";
//////////        Starting of first drop downlist /////////
echo "<select name='TERM' onchange=\"reload(this.form)\"><option value=''>Select Term</option>";
while($row = mysql_fetch_array($quer2)) { 
if($row['TERM']==$cat){echo "<option selected value='$row[TERM]'>$row[TERM]</option>"."<BR>";}
else{echo  "<option value='$row[TERM]'>$row[TERM]</option>";}
}
echo "</select>";
//////////////////  This will end the first drop down list ///////////
echo "<br />";
//////////        Starting of second drop downlist /////////
echo "<select name='CURR' onchange=\"reload3(this.form)\"><option value=''>Select Curriculum</option>";
while($row = mysql_fetch_array($quer)) { 
if($row['CURR']==$cat3){echo "<option selected value='$row[CURR]'>$row[CURR]</option>"."<BR>";}
else{echo  "<option value='$row[CURR]'>$row[CURR]</option>";}
}
echo "</select>";
//////////////////  This will end the second drop down list ///////////
echo "<br />";

//////////        Starting of third drop downlist /////////
echo "<select name='COURSE' onChange='document.f1.submit()'><option value=''>Select Course</option>";
while($row = mysql_fetch_array($quer3)) { 
echo  "<option value='$row[COURSE]'>$row[COURSE]</option>";
}
echo "</select>";
//////////////////  This will end the third drop down list ///////////
echo "</form>";
?>

   </div>                  
</div>
                  <div class="col-2 maxheight" style="margin-left: 0"><h2><b><b>textbook information</b></b></h2>
              		<iframe id="content">*****Books will be listed here after selection is made*****</iframe>
                  </div>
<script type="text/javascript"> Cufon.now(); </script>
</body>
</html>

 

Hi.

For the first question - I would put each drop down in it's own div and then reload the div onchange not reload the form in the same way I have done with the code posted on Aug 1 at 3:12. The line where this is done is:

<select name="catId" onChange="get_subcat(this.value);get_subcat2(0)">.

 

Can you post your db contents too - that way I could rebuild what you have so it'll be easier to help.

 

For the second one - I'm not too sure I get you. What do you mean about submitting into an iframe?

#1

I'm not sure how to export my DB in the same way that Geek did, so if this doesn't work for you let me know how I should export it.

I'm using one table. I have included the first 10 listings as there are over 900 in the table.

 

-- phpMyAdmin SQL Dump
-- version 3.3.9.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: May 13, 2011 at 09:22 AM
-- Server version: 5.0.92
-- PHP Version: 5.2.9

SET AUTOCOMMIT=0;
START TRANSACTION;


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `DB`
--

-- --------------------------------------------------------

--
-- Table structure for table `SUMMER`
--

DROP TABLE IF EXISTS `SUMMER`;
CREATE TABLE IF NOT EXISTS "SUMMER" (
  "id" int(11) NOT NULL,
  "TERM" varchar(4) default NULL,
  "CURR" varchar(4) default NULL,
  "COURSE" varchar(12) default NULL,
  "TITLE" varchar(60) default NULL,
  "AUTHOR" varchar(13) default NULL,
  "EDITION" varchar(4) default NULL,
  "INSTRUCTOR" varchar(15) default NULL,
  "ISBN" varchar(10) default NULL,
  "ALT ISBN" varchar(10) default NULL,
  "PUBLISHER" varchar(5) default NULL,
  "NEW PRICE" decimal(18,15) default NULL,
  "USED PRICE" decimal(17,15) default NULL,
  PRIMARY KEY  ("id")
) AUTO_INCREMENT=902 ;

--
-- Dumping data for table `SUMMER`
--

INSERT INTO `SUMMER` (`id`, `TERM`, `CURR`, `COURSE`, `TITLE`, `AUTHOR`, `EDITION`, `INSTRUCTOR`, `ISBN`, `ALT ISBN`, `PUBLISHER`, `NEW PRICE`, `USED PRICE`) VALUES
(1, 'SU11', 'ACCT', '2101', 'FINANCIAL ACCT UGA CUSTOM (1SS)', 'WILD', '00', 'BHANDARKAR12989', '0390306916', '0390306916', 'PRIMU', 108.150000000000000, 81.099999999999990),
(2, 'SU11', 'ACCT', '2101', 'FINA & MANAGERIAL ACCT SG CH 1-15 ', 'WARREN', '10TH', 'LYMAN', '0324664648', '0324664648', 'CENGA', 38.750000000000000, 29.050000000000000),
(3, 'SU11', 'ACCT', '2101', 'FINA & MANAGERIAL ACCT WKPR CH 1-15 ', 'WARREN', '10TH', 'LYMAN', '0324664664', '0324664664', 'CENGA', 40.600000000000000, 30.450000000000000),
(4, 'SU11', 'ACCT', '2101', 'FINA & MANAGERIAL ACCT WKPR CH 1-15 ', 'WARREN', '10TH', 'BLAIR/WILLIAMS', '0324664664', '0324664664', 'CENGA', 40.600000000000000, 30.450000000000000),
(5, 'SU11', 'ACCT', '2102', 'CORNERSTONES OF MGRL ACCT (2SS) ', 'MOWEN/HEITGER', '3RD', 'MATTHEWS 02991', '0324660138', '0324660138', 'CENGA', 219.700000000000000, 99.999999999999999),
(6, 'SU11', 'ACCT', '2102', 'CORNERSTONES OF MGRL ACCT LLF VALUE ED (2SS) ', 'MOWEN/HEITGER', '3RD', 'MATTHEWS 02991', '1111527504', '1111527504', 'CENGA', 138.750000000000000, 99.999999999999999),
(7, 'SU11', 'ACCT', '2102', 'FINA & MANAGERIAL ACCT SG CH 16-26 ', 'WARREN', '10TH', 'LYMAN', '0324664656', '0324664656', 'CENGA', 38.750000000000000, 29.050000000000000),
(8, 'SU11', 'ACCT', '7651', 'PRIN OF FRAUD EXAMINATION (MAY)', 'WELLS', '3RD', 'CARPENTER 93002', '0470646292', '0470646292', 'WILEY', 168.750000000000000, 99.999999999999999),
(9, 'SU11', 'ACCT', '2101/2102', 'FINA & MANAGERIAL ACCT ', 'WARREN', '10TH', 'ALL', '0324663811', '0324663811', 'CENGA', 200.000000000000000, 99.999999999999999),
(10, 'SU11', 'ACCT', '2101/2102', 'FINA & MANA ACCT ', 'WARREN', '10TH', 'STAFF', '0324664575', '0324664575', 'CENGA', 146.700000000000000, 99.999999999999999),

 

 

#2

currently the form submits the result into an iframe...

echo "<form method=post name=f1 action='dd3ck.php' target='content'>";

echo "<select name='COURSE' onChange='document.f1.submit()'><option value=''>Select Course</option>";

 

Instead, I would like to submit the results into a div on the page.

I've got the first and the second drop down to populate, but I cannot get the third.

 

config.php

<?php

//////////// Change the data part only with your database login details /////////////////
$dbservertype='mysql';
// hostname or ip of server
$servername='localhost';
$dbusername='';
$dbpassword='';
$dbname='';

//////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////
////// DONOT EDIT BELOW  /////////
///////////////////////////////////////

connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
?>

 

 

 

main.php

<html>
<head>
<title>Textbooks</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/cufon-replace.js"></script>
<!--[if lt IE 7]>
<![endif]-->

<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
// If you have any problem contact me at http://roshanbh.com.np

function getXMLHTTP() { //fuction to return the xml http object
      var xmlhttp=false;   
      try{
         xmlhttp=new XMLHttpRequest();
      }
      catch(e)   {      
         try{         
            xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(e){
            try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e1){
               xmlhttp=false;
            }
         }
      }
          
      return xmlhttp;
    }
   
   function get_CURR(TERM) {      
      var strURL="findCURR.php?TERM="+TERM;
      var req = getXMLHTTP();
      
      if (req) {
         
         req.onreadystatechange = function() {
            if (req.readyState == 4) {
               // only if "OK"
               if (req.status == 200) {                  
                  document.getElementById('CURR_div').innerHTML=req.responseText;                  
               } else {
                  alert("There was a problem while using XMLHTTP:\n" + req.statusText);
               }
            }            
         }         
         
         req.open("GET", strURL, true);
         req.send(null);
      }      

   }
   
   function get_COURSE(CURR) {      
      var strURL="findCOURSE.php?CURR="+CURR;
      var req = getXMLHTTP();
      
      if (req) {
         
         req.onreadystatechange = function() {
            if (req.readyState == 4) {
               // only if "OK"
               if (req.status == 200) {                  
                  document.getElementById('COURSE_div').innerHTML=req.responseText;                  
               } else {
                  alert("There was a problem while using XMLHTTP:\n" + req.statusText);
               }
            }            
         }         
         req.open("GET", strURL, true);
         req.send(null);
      }
            
   }
   
</script>
</head>
<body id="page2" onload="new ElementMaxHeight();">


<h2><b><b>make your selection</b></b></h2>

<form method=post name=f1 action='dd3ck.php'>
<div id="first_drop_down">
<select name="TERM" onChange="get_CURR(this.value);get_COURSE(0)">
<option>Select Term</option>
<?php
require "config.php";
$query=("SELECT DISTINCT TERM FROM SUMMER");
$result=mysql_query($query);
while($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['TERM']?>><?php echo $row['TERM']?></option>
<? } ?>
</select>
</div>

<div id="CURR_div">
<?php include ('findCURR.php'); ?>
</div>

<div id="COURSE_div">
<?php include ('findCOURSE.php'); ?>
</div>
</form>

<div class="col-2 maxheight" style="margin-left: 0">
<h2><b><b>textbook information</b></b></h2> 
<iframe id="iframe" name="iframe" width="100%" height="80%">
  <p>Your browser does not support iframes.</p>
</iframe>
</div>

<script type="text/javascript"> Cufon.now(); </script>
</body>
</html>

 

findCURR.php

*************************************************************************
<!--//---------------------------------+
//  Developed by Roshan Bhattarai    |
//	http://roshanbh.com.np           |
//  Contact for custom scripts       |
//  or implementation help.          |
//  email-nepaliboy007@yahoo.com     |
//---------------------------------+-->
<?
#### Roshan's Ajax dropdown code with php
#### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
#### if you have any problem contact me at http://roshanbh.com.np
#### fell free to visit my blog http://roshanbh.com.np
?>

<? $TERM=intval($_GET['TERM']);
   $CURR=intval($_GET['CURR']);
   $COURSE=intval($_GET['COURSE']);

require "config.php";

if ($TERM!=0)
{
$query="SELECT DISTINCT CURR FROM SUMMER where TERM='$TERM' order by CURR";
$result=mysql_query($query);
}
else
{
$query="SELECT DISTINCT CURR FROM SUMMER order by CURR";
$result=mysql_query($query);
}
?>
<select name="CURR" onchange="get_COURSE(this.value)">

<option>Select Curriculum</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['CURR']?>><?=$row['CURR']?></option>
<? } ?>

</select>
*************************************************************************

 

findCOURSE.php

*************************************************************************
<!--//---------------------------------+
//  Developed by Roshan Bhattarai    |
//	http://roshanbh.com.np           |
//  Contact for custom scripts       |
//  or implementation help.          |
//  email-nepaliboy007@yahoo.com     |
//---------------------------------+-->
<?
#### Roshan's Ajax dropdown code with php
#### Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
#### if you have any problem contact me at http://roshanbh.com.np
#### fell free to visit my blog http://roshanbh.com.np
?>

<? $CURR=intval($_GET['CURR']);
   $COURSE=intval($_GET['COURSE']);

require "config.php";

if ($CURR!=0)
{
$query="SELECT DISTINCT COURSE FROM SUMMER where CURR='$CURR' order by COURSE";
$result=mysql_query($query);
}
else
{
$query="SELECT DISTINCT COURSE FROM SUMMER order by COURSE";
$result=mysql_query($query);
}
?>
<select name="COURSE">

<option>Select Course</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['COURSE']?>><?=$row['COURSE']?></option>
<? } ?>
</select>
*************************************************************************

I don't know if this helps identify my problem, but in IE I am getting a 'document.getElementById(...)' is null or not an object error message for

 

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

   }

 

You can see the response is coming back ok if you change the get_COURSE function to what's below.

There is an extra line displaying the response text to screen: alert(req.responseText);

 

  function get_COURSE(CURR) {     

      var strURL="findCOURSE.php?CURR="+CURR;

      var req = getXMLHTTP();

      if (req) {

       

        req.onreadystatechange = function() {

            if (req.readyState == 4) {

              // only if "OK"

              if (req.status == 200) {   

alert(req.responseText);  

                  document.getElementById('COURSE_div').innerHTML=req.responseText;             

  } else {

                  alert("There was a problem while using XMLHTTP:\n" + req.statusText);

              }

            }           

        }       

        req.open("GET", strURL, true);

        req.send(null);

      }

           

  }

 

I can get all 3 populating by changing the 2nd & 3rd divs to below: 

 

<div id="CURR_div">

</div>

 

<div id="COURSE_div">

</div>

 

Can't trace the problem that prevents the page working with your current code but this solution seems to work nicely.

Hope this helps you out.

I have the page loading fine here:

http://www.piano-tuna.com/ajax/main.php

 

If you look at your page source the code is being truncated at the second div.

Did you try changing the curr and course div to below?:

 

<div id="CURR_div">

</div>

 

<div id="COURSE_div">

</div>

You are a GENIUS!  :D Not sure what I had wrong, but I just copied your code and now it works. Thank You Thank You Thank You!

 

Now, if that wasn't enough....  :-[  I am playing around with how to submit the results I want (from dd3ck.php) into a div on that page. If you still have anything left to give me I would surely appreciate it.

 

Again, THANKS man, you Rock!

Well I can't test this out cause of work restrictions but this is what I reckon should work.

First you need to create a new function under the function "function get_COURSE(CURR)".

It's the same function again but calling your dd3 page and updating an additional div:

 

  function get_Results(<your variables>) {     

      var strURL="dd3ck.php?<your variables>="+<your variables>;

      var req = getXMLHTTP();

     

      if (req) {

       

        req.onreadystatechange = function() {

            if (req.readyState == 4) {

              // only if "OK"

              if (req.status == 200) {                 

                  document.getElementById('RESULTS_div').innerHTML=req.responseText;                 

              } else {

                  alert("There was a problem while using XMLHTTP:\n" + req.statusText);

              }

            }           

        }       

        req.open("GET", strURL, true);

        req.send(null);

      }

           

  }

 

Then just before the line </form> you need to add something like this:

<input type="button" value="Click Here" onClick="get_Results();">

 

And finally add a new div.

<div id="RESULTS_div">

</div>

 

I'm pretty sure this should get you going along the right lines.

I really appreciate your help.

 

I have been fooling around with it all day and cannot get it to work. I don't know if I am using the wrong variables or what exactly I am doing wrong.

 

I basically want everything in dd3ck.php to load into the div.

 

dd3ck.php

<html><body>

<?

require "config.php";

 

$TERM=$_POST['TERM'];

$CURR=$_POST['CURR'];

$COURSE=$_POST['COURSE'];

$TITLE=$_POST['TITLE'];

$AUTHOR=$_POST['AUTHOR'];

$PUBLISHER=$_POST['PUBLISHER'];

$INSTRUCTOR=$_POST['INSTRUCTOR'];

 

 

$query = "SELECT * FROM SUMMER WHERE TERM = '$TERM' AND CURR = '$CURR' AND COURSE = '$COURSE' order by INSTRUCTOR";

 

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

 

$display_string = "<table style='color:#fff;'>";

 

while($row = mysql_fetch_array($qry_result)){

$display_string .= "<tr>";

$display_string .= "<td colspan=3><b>Instructor: $row[iNSTRUCTOR]</b></td>";

        $display_string .= "</tr>";

 

$display_string .= "<tr>";

$display_string .= "<td> </td>";

        $display_string .= "</tr>";

 

$display_string .= "<tr>";

$display_string .= "<td colspan=2 rowspan=4><img src=\"Merchant5/$row[thumbnail]\" /></td>";

$display_string .= "<td><a href=\"Merchant5/$row[TITLE]\" onclick=\"return GB_showCenter('Product', this.href)\"> $row[TITLE]</a></td>";

$display_string .= "</tr>";

 

$display_string .= "<tr>";

$display_string .= "<td>Author: $row[AUTHOR]</td>";

$display_string .= "</tr>";

 

$display_string .= "<tr>";

$display_string .= "<td>Publisher: $row[PUBLISHER] <br /> </td>";

$display_string .= "</tr>";

 

$display_string .= "<tr>";

$display_string .= "<td><a href=\"Merchant5/$row[TITLE]\" onclick=\"return GB_showCenter('Product', this.href)\"><img src=\"Merchant5/buybooksnow.png\" /></a></td>";

$display_string .= "</tr>";

 

$display_string .= "<tr>";

$display_string .= "<td colspan=3><br /><hr /><br /></td>";

$display_string .= "</tr>";

}

//echo "Query: " . $query . "<br />";

$display_string .= "</table>";

echo $display_string;

?>

</body></html>

 

 

When I input all the variables...

function get_Results(TERM,CURR,COURSE) {     
      var strURL="dd3ck.php?TERM="+TERM+"&CURR="+CURR+"&COURSE="+COURSE;

 

the dropdowns all populate and the text in the RESULTS_div goes away, but the result doesn't display..

 

In the new function you've created, below the line:

if (req.status == 200) {                 

 

Could you add this line:

alert("Response "+req.responseText);

 

What is printed to screen when you submit your form?

nothing is printed when I submit the form...

 

http://www.dawgwear.net/main.php

 

function get_Results(COURSE) {   
      var strURL="dd3ck.php?COURSE="+COURSE;
      var req = getXMLHTTP();
     
      if (req) {
         
         req.onreadystatechange = function() {
            if (req.readyState == 4) {
               // only if "OK"
               if (req.status == 200) {     
                  document.getElementById('RESULTS_div').innerHTML=req.responseText;               
			  } else {
                  alert("Response "+req.responseText); 
               }
            }            
         }         
         req.open("GET", strURL, true);
         req.send(null);
      }
            
   }

 

function get_Results(COURSE) {   
      var strURL="dd3ck.php?"
      var req = getXMLHTTP();
     
      if (req) {
         
         req.onreadystatechange = function() {
            if (req.readyState == 4) {
               // only if "OK"
               if (req.status == 200) {     
                  document.getElementById('RESULTS_div').innerHTML=req.responseText;               
			  } else {
                  alert("Response "+req.responseText); 
               }
            }            
         }         
         req.open("GET", strURL, true);
         req.send(null);
      }
            
   }

 

function get_Results(TERM,CURR,COURSE) {   
      var strURL="dd3ck.php?TERM="+TERM+"&CURR="+CURR+"&COURSE="+COURSE;
      var req = getXMLHTTP();
     
      if (req) {
         
         req.onreadystatechange = function() {
            if (req.readyState == 4) {
               // only if "OK"
               if (req.status == 200) {     
                  document.getElementById('RESULTS_div').innerHTML=req.responseText;               
			  } else {
                  alert("Response "+req.responseText); 
               }
            }            
         }         
         req.open("GET", strURL, true);
         req.send(null);
      }
            
   }

You've put the alert in the wrong place.

Can you change that last function to this:

 

function get_Results(TERM,CURR,COURSE) { 

      var strURL="dd3ck.php?TERM="+TERM+"&CURR="+CURR+"&COURSE="+COURSE;

      var req = getXMLHTTP();

   

        if (req) {

       

        req.onreadystatechange = function() {

            if (req.readyState == 4) {

              // only if "OK"

              if (req.status == 200) {       

                  alert("Response "+req.responseText);  

                  document.getElementById('RESULTS_div').innerHTML=req.responseText;                 

              } else {

                  alert("There was a problem while using XMLHTTP:\n" + req.statusText);

              }

            }           

        }       

        req.open("GET", strURL, true);

        req.send(null);

      }

           

  }

Oh, wow, sorry!

 

This is the alert

Response <style type="text/css">
A:link {color: white;}
A:hover {color: red;}
</style>


<!doctype html public "-//w3c//dtd html 3.2//en">

<html>
<head>
<title>Textbooks</title>
<script type="text/javascript">
    var GB_ROOT_DIR = "greybox/";
</script>
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJS_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<link href="greybox/gb_styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
</head>
<body>
<table style='color:#fff;'></table></body></html>

 

It's not generating the php...?

No worries.

Well cause it's missing out the whole of the while bit I guess the query is not returning anything.

But I'm also not sure the while loop is using the right syntax.

Could you try changing the page to this and see what happens?

 

<html><body>

<?

require "config.php";

 

$TERM=$_POST['TERM'];

$CURR=$_POST['CURR'];

$COURSE=$_POST['COURSE'];

$TITLE=$_POST['TITLE'];

$AUTHOR=$_POST['AUTHOR'];

$PUBLISHER=$_POST['PUBLISHER'];

$INSTRUCTOR=$_POST['INSTRUCTOR'];

 

$query = "SELECT * FROM SUMMER WHERE TERM = '$TERM' AND CURR = '$CURR' AND COURSE = '$COURSE' order by INSTRUCTOR";

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

 

$display_string = "";

while($row = mysql_fetch_array($qry_result))

{

$display_string .=<tr><td colspan=3><b>Instructor: $row[iNSTRUCTOR]</b></td></tr><tr><td> </td></tr><tr><td colspan=2 rowspan=4><img src=\"Merchant5/$row[thumbnail]\" /></td><td><a href=\"Merchant5/$row[TITLE]\" onclick=\"return GB_showCenter('Product', this.href)\"> $row[TITLE]</a></td></tr><tr><td>Author: $row[AUTHOR]</td></tr><tr><td>Publisher: $row[PUBLISHER] <br /> </td></tr><tr><td><a href=\"Merchant5/$row[TITLE]\" onclick=\"return GB_showCenter('Product', this.href)\"><img src=\"Merchant5/buybooksnow.png\" /></a></td></tr><tr><td colspan=3><br /><hr /><br /></td></tr>

}

echo "<table style='color:#fff;'>";

echo $display_string;

echo "</table>";

 

?>

</body></html>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.