Avatar of capsoftuk
capsoftukFlag for United Kingdom of Great Britain and Northern Ireland

asked on 

PHP MySQL Dynamic Drop-down boxes using AJAX

Hi there,

I'm currently working on a PHP Upload script for work, and I'm a bit rusty on the PHP side but not too bad. Basically, we have a large library of forms which are all split into formpacks, which are then split into categories. So what I have at the moment is a single drop-down (populated from a mysql database) as the user comes to the page. From that drop-down, the user selects a category, and then clicks a button to show up the next drop-down, which contains formpacks, and so on. Basically, what I want to do is change the code so that instead of having to click a button to show up the next dropdown, the user would just click on the category in the drop-down and the script would use AJAX to automatically populate the next drop-down list. Once you get to the final, forms dropdown list, the filename of the form plus the categoryid and the formpackid should be sent through to the next page in a querystring.

I have an example that I've been working on, but I am not having any luck getting it to work. I'm not totally sure how AJAX works but I would love to know more. If anyone out there knows how to resolve this, I would be very grateful. I attach code below, with the JS file, PHP code and
// =====================
// JS File
// =====================
var xmlHttp;
 
function showUser(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="new.php"
url=url+"?q="+str
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("formpacks").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;
 
}
// =====================
// PHP File
// =====================
 
<?php
 
error_reporting(E_ALL);
 
// Makes database connection
 
 
// I have omitted database connection variables, suffice to say the 
// script works to call data from the database
 
 
$php_self = $_SERVER['PHP_SELF'];
 
 
$getCapformCategoriesQuery = "SELECT Title FROM category";
$getCapformCategoriesResult = mysql_query($getCapformCategoriesQuery) or die(mysql_error());
 
 
$details = array(4);
 
if(isSet($_POST['fileSubmit']))
{
 
 
 
	$target_path = "http://localhost/upload/";
 
	$target_path = $target_path . basename( $_FILES['uploadFile']['name']);
 
	if(move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target_path))
	{
	    echo "The file ".basename( $_FILES['uploadFile']['name'])." has been uploaded";
	}
	else
	{
	    echo "There was an error uploading the file, please try again! target path = ". $target_path ." file ";
	}
 
 
}
 
 
 
 
?>
<HTML>
<HEAD>
<TITLE> This is a test of arrays </TITLE>
 
<script src="selectuser.js"></script>
</HEAD>
<BODY>
 
 
<form enctype="multipart/form-data" method=POST action="<?php $_SERVER['PHP_SELF']; ?>">
 
<P><input type="file" name="uploadFile">
<P><input type="submit" name="fileSubmit" value="Check filename">
 
</form>
 
<form method=POST action="<?php $_SERVER["PHP_SELF"]; ?>">
 
<P><SELECT name="categories" onChange="showUser(this.value)">
 
	<?php
		$counter = 0;
		while($capformCategoriesArray = mysql_fetch_array($getCapformCategoriesResult))
		{
 
				printf("<option value='%s'> %s </option>", $counter, $capformCategoriesArray['Title']);
				echo $counter;
				$counter ++;
 
 
		}
 
	?>
 
 
</SELECT>
<input type="submit" name="catSubmit" value="Check Category">
 
 
 
	<?php
 
		if(isSet($_POST['catSubmit']) || isSet($_POST['formsubmit']))
				{
 
					print("<P><SELECT id='formpacks'>");
					$categoryID = $_POST['categories'] + 1;
 
 
 
 
					$getFormpacksQuery = "SELECT * FROM formpacks WHERE CategoryID = '$categoryID'";
					$getFormpacksResult = mysql_query($getFormpacksQuery) or die(mysql_error());
 
 
					$counter = 0;
					while($formpackArray = mysql_fetch_array($getFormpacksResult))
					{
						printf("<option value='%s'> %s </option>", $counter, $formpackArray['Title']);
					 	$counter ++;
					}
					print("</SELECT>");
					print("<input type='submit' name='formsubmit' value='Get Forms'");
					print("<input type='hidden' name='catID' value='$categoryID'");
 
 
					print("<P><SELECT name='forms'>");
 
					if(isSet($_POST['formpacks']))
					{
						$formpackID = $_POST['formpacks'];
 
						$getFormsQuery = "SELECT * FROM forms WHERE CategoryID = '$formpackID'";
					}
					else
					{
						$getFormsQuery = "SELECT * FROM forms WHERE CategoryID = 1";
					}
 
					$getFormsResult = mysql_query($getFormsQuery) or die (mysql_error());
 
 
					$counter = 0;
					while ($formArray = mysql_fetch_array($getFormsResult))
					{
						printf("<option value='%s'> %s - %s </option>", $counter, $formArray['Filename'], $formArray['Description']);
					 	$counter ++;
					}
 
					print("</SELECT>");
					print("<P><input type='submit' name='formnameSubmit' value='Get Form Value'>");
					print("<input type='hidden' name='formpackID' value='$formpackID'");
 
		}
		if(isSet($_POST['formnameSubmit']))
		{
 
			$formID = $_POST['forms'];
			$getFormDetailsQuery = "SELECT * FROM forms WHERE UniqueID = '$formID'";
			$getFormDetailsResult = mysql_query($getFormDetailsQuery) or die (mysql_error());
			$getFormDetailsArray = mysql_fetch_array($getFormDetailsResult);
 
			$formUniqueID = $getFormDetailsArray['UniqueID'];
			$formName = $getFormDetailsArray['Filename'];
			print("<P> <a href='getFile.php?categoryID=$categoryID&formpackID=$formpackID&formID=$formUniqueID&formname=$formName'> Go to Next Step </a>");
 
		}
	?>
 
 
 
</form>
 
 
 
 
</BODY>
</HTML>

Open in new window

PHPAJAX

Avatar of undefined
Last Comment
capsoftuk
Avatar of tg_wilk
tg_wilk

I'd put the code to get the categories in a separate script (below). The easier way is to return data with xml rather then html. It is just a draft so there can be some typos
==============
PHP for AJAX categories (say 'categories.php')
==============
<?php
$parent = (isset($_GET['parent'])?(int)$_GET['parent']:0; //which category was chosen in previous select
$populate = (isset($_GET['populate'])?(int)$_GET['populate']:0;
 
//do your magic with the database to get all categories for parent $parent
//in case of parent=0 get first level categories
 
//when you're done output xml
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="utf-8" ?>
<categories>';
foreach ($category_from_database as $c) echo "<category id=\"$c[id]\">$c[name]</category>\n"
echo "<populate>$populate</populate>
echo '</categories>';
 
=========================
on your page with selects
=========================
<form name="category_selector">
<select id="cat1" name="cat1" onChange="categoryChanged(this,2);">
//populate this at the beginning, no need for ajax here
<option value="1">Category 1</option>
<option value="2">Category 2</option>
</select>
<select id="cat2" name="cat2" onChange="categoryChanged(this,3);">
</select>
<select id="cat3" name="cat3" onChange="DoSomethingDifferent(this);">
 
<script type="text/javascript">
function categoryChanged(changed,populate)
{
  var cat_id = changed.value;
  var url = 'categories.php?parent='+cat_id+'&populate='+populate;
  xmlHttp=GetXmlHttpObject()
  if (xmlHttp==null)
  {
   alert ("Browser does not support HTTP Request")
   return
  }
xmlHttp.onreadystatechange=categoryStateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
 
function categoryStateChanged()
{
        {
        	try
		{
	
			if (xmlHttp.readyState == 4){
				if (xmlHttp.status == 200)
				{
					if (xmlHttp.responseXML)
					{
						var populate = xmlHttp.responseXML.getElementsByTagName('populate');
						var select_p = 'cat'+populate[0].firstChild.data;
						//clear select to populate
						var select_object = document.getElementById(select_p);
						for (i=select_object.length; i >= 0; i--) select_object[i]=null;
						var categories = xmlHttp.responseXML.getElementsByTagName('category');
						for (i=0; i<categories.length;i++)
						{
							var name = s[i].firstChild.data;
							var value = s[i].getAttribute('id');
							select_object[select_object.length]= new Option(name,value);
						}
					}
					else
					{
						//do some error reporting
					}
				}
			}
		}
		catch (err)
		{
			//more error reporting
		}
}
 
categoryChanged(document.getElementById('cat1'),2);
</script>
</form>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of tg_wilk
tg_wilk

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of capsoftuk
capsoftuk
Flag of United Kingdom of Great Britain and Northern Ireland image

ASKER

thanks for the help - unfortunately, due to time constraints, we've just used plain-jane php, but I will test your code when I get round to it and see if it works. Cheers :)
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo