I am wanting to create a dynamic drop down list based on mysql database and tables. I searched around the net and the closest I came was to .php
I have implimented this code as per example, the first drop down box works correctly however the second does not get populated once a 'category' is chosen.
The code is:
main.php
<html>
<body>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<form name="testform" method='POST' action='mainck.php'>Name:<input type=text name=fname>
Select first one <select name=cat onchange="AjaxFunction(this.value);">
<option value=''>Select One</option>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<select name=subcat>
</select><input type=submit value=submit>
</form>
</body>
</html>
and dd.php is
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select subcategory from subcategory where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[subcategory]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>
As mentioned, main.php loads and populates the first drop down box correctly. Once a value is chosen nothing appears in the second box. To test, I changed the mysql query in dd.php from
$q=mysql_query("select subcategory from subcategory where cat_id='$cat_id'");
to
$q=mysql_query("select subcategory from subcategory where cat_id=1");
This then populates the second box when a 'category' is chosen. I think the chosen value is not passing from main.php to dd.php correctly with the
$cat_id=$_GET['cat_id'];
Any help on this would be appreciated. I have a feeling this is something small but cant quite put my finger on it.
As always many thanks in advance. UPDATED QUESTION
main.php
<form name='testform' method='POST' action='mainck.php'>
Name: <input type='text' name='fname'>
Select first one
<select name='cat' onchange='AjaxFunction(this);'>
<option value=''>Select One</option>
<?php
require "config.php";// connection to database
// I will continue to use mysql_query(), but please migrate you code to
// PDO or MySQLi ASAP
$query = "
SELECT cat_id,category
FROM categories
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "<option value='{$row['cat_id']}'>{$row['category']}</option>";
}
?>
</select>
<select name='subcat' id='subcat_select'>
</select>
<input type='submit' value='Submit'>
</form>
dd.php
<?php
require "config.php";
$query = "
SELECT packcode
FROM skudata
WHERE cat_id='".mysql_real_escape_string($_GET['cat_id'])."' ";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['packcode'];
}
echo json_encode($array);
?>
with the changes Dave Added, I cant get the new mysql tables and reference columns working. Have tested the mysql and it works well. Any help is appreciated.
Thanks,
I am wanting to create a dynamic drop down list based on mysql database and tables. I searched around the net and the closest I came was to http://www.plus2net./php_tutorial/ajax_drop_down_list.php
I have implimented this code as per example, the first drop down box works correctly however the second does not get populated once a 'category' is chosen.
The code is:
main.php
<html>
<body>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<form name="testform" method='POST' action='mainck.php'>Name:<input type=text name=fname>
Select first one <select name=cat onchange="AjaxFunction(this.value);">
<option value=''>Select One</option>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<select name=subcat>
</select><input type=submit value=submit>
</form>
</body>
</html>
and dd.php is
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select subcategory from subcategory where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[subcategory]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>
As mentioned, main.php loads and populates the first drop down box correctly. Once a value is chosen nothing appears in the second box. To test, I changed the mysql query in dd.php from
$q=mysql_query("select subcategory from subcategory where cat_id='$cat_id'");
to
$q=mysql_query("select subcategory from subcategory where cat_id=1");
This then populates the second box when a 'category' is chosen. I think the chosen value is not passing from main.php to dd.php correctly with the
$cat_id=$_GET['cat_id'];
Any help on this would be appreciated. I have a feeling this is something small but cant quite put my finger on it.
As always many thanks in advance. UPDATED QUESTION
main.php
<form name='testform' method='POST' action='mainck.php'>
Name: <input type='text' name='fname'>
Select first one
<select name='cat' onchange='AjaxFunction(this);'>
<option value=''>Select One</option>
<?php
require "config.php";// connection to database
// I will continue to use mysql_query(), but please migrate you code to
// PDO or MySQLi ASAP
$query = "
SELECT cat_id,category
FROM categories
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "<option value='{$row['cat_id']}'>{$row['category']}</option>";
}
?>
</select>
<select name='subcat' id='subcat_select'>
</select>
<input type='submit' value='Submit'>
</form>
dd.php
<?php
require "config.php";
$query = "
SELECT packcode
FROM skudata
WHERE cat_id='".mysql_real_escape_string($_GET['cat_id'])."' ";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['packcode'];
}
echo json_encode($array);
?>
with the changes Dave Added, I cant get the new mysql tables and reference columns working. Have tested the mysql and it works well. Any help is appreciated.
Thanks,
Share Improve this question edited May 28, 2012 at 15:07 Smudger asked May 28, 2012 at 11:09 SmudgerSmudger 10.8k29 gold badges107 silver badges180 bronze badges 2- 1 url=url+"?cat_id="+cat_id; url=url+"&sid="+Math.random(); URL overwrite i guess – swapnesh Commented May 28, 2012 at 11:15
- Hi Swapnesh, thanks for this. I changed these two lines without success. any other advice? – Smudger Commented May 28, 2012 at 11:32
2 Answers
Reset to default 4Firstly, the small thing that is preventing you code from working is the value your are passing to the function. For a <select>
element this.value
will not work. Instead, you need to use this.options[this.selectedIndex].value
. Like so:
<select name=cat onchange="AjaxFunction(this.options[this.selectedIndex].value);">
Now for some ments about your code:
- Never use
eval()
. Ever. In any language. The correct use cases are so few and far between that it's much simpler to just say "Never use it". - Don't use the
mysql
extension. UsePDO
orMySQLi
instead. - You have a huge SQL Injection hole in your code.
- Please indent your code sensibly. It makes it much easier to debug. That higgledy-piggledy lump you posted was almost impossible to read.
- Don't use
document.elementName
to access elements on the page. Give your elements ID's and usedocument.getElementById('elementId')
instead - it works everywhere, which named elements does not. - Don't use PHP short open tags
<?
, use the full<?php
tag - again, it works everywhere, which short tags do not.
Here is how I would write your code:
main.php
<html>
<head>
<!-- Omitting the <head> is very bad practice... -->
<title>My Page</title>
<script type='text/javascript'>
function GetAjaxObject () {
// Wrap the code for fetching an AJAX object in a separate function
// so it can be easily re-used
if (window.XMLHttpRequest !== undefined) {
return new XMLHttpRequest();
}
var xhr = null;
var axo = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var o in axo) {
try {
xhr = new ActiveXObject(axo[o]);
} catch (e) {}
}
if (xhr !== null) {
return xhr;
} else {
throw new Error('Your browser does not support AJAX');
}
}
function ChangeSelect (element) {
// We are now passing the select element itself in, not just a value
var xhr, url;
// Fetch an AJAX object
try {
var xhr = GetAjaxObject();
} catch (e) {
alert(e.message);
return;
}
// Build the URL
url = "dd.php"
+ "?cat_id="+element.options[element.selectedIndex].value
+ "&sid="+Math.random();
// If it still doesn't work, unment this line to inspect the url
// alert(url);
// Define the readystatechange callback
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) { // Don't forget to check the status code
// I shall leave this eval() here for now, but really you should
// use a safe JSON library like http://www.json/js.html
var myarray = eval(httpxml.responseText);
// Start by getting a safe reference to the destination select
var dest = document.getElementById('subcat_select');
// Before adding new we must remove previously loaded elements
for (j = dest.options.length - 1; j >= 0; j--) {
dest.remove(j);
}
// Loop data from the server and create new options
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("option");
optn.text = myarray[i];
optn.value = myarray[i];
dest.options.add(optn);
}
} else {
alert("Server returned error " + xhr.status);
}
}
};
// Start the request
httpxml.open("GET", url, true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name='testform' method='POST' action='mainck.php'>
Name: <input type='text' name='fname'>
Select first one
<select name='cat' onchange='AjaxFunction(this);'>
<option value=''>Select One</option>
<?php
require "config.php";// connection to database
// I will continue to use mysql_query(), but please migrate you code to
// PDO or MySQLi ASAP
$query = "
SELECT *
FROM categories
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "<option value='{$row['cat_id']}'>{$row['category']}</option>";
}
?>
</select>
<select name='subcat' id='subcat_select'>
</select>
<input type='submit' value='Submit'>
</form>
</body>
</html>
dd.php
<?php
require "config.php";
$query = "
SELECT subcategory
FROM subcategory
WHERE cat_id='".mysql_real_escape_string($_GET['cat_id'])."'
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['subcategory'];
}
echo json_encode($array);
?>
this code not worknig as all this is main.php file
<script type="text/javascript">
function AjaxFunction(cat_id)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
var myarray=eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.testform.subcat.options.length-1;j>=0;j--)
{
document.testform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<form name="testform" method='POST' action='mainck.php'>
Select first one <select name=cat onchange="AjaxFunction(this.value);">
<option value=''>Select One</option>
<?
require "config.php";// connection to database
$q=mysql_query("select * from it_category ");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<select name=subcat>
</select><input type=submit value=submit>
</form>
</body>
</html>
and this is dd.php
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select * from it_subcategory where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[subcategory]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>