/    Sign up×
Community /Pin to ProfileBookmark

problem with dynamic dropdown list

I have a script that contains 3 dropdown list. 1 country 2 region 3 city
I wonder how i can populate the script from database
because if i leave it like this works fine but i want to extract the country from database mysql. if somebody knows how can i do that please help.

to post a comment
JavaScript

11 Comments(s)

Copy linkTweet thisAlerts:
@BalistikBillSep 24.2009 — This cannot be acheived with Javascript you must use PHP to access your Mysql database to create the dropdown list.

[code=php]
function createDropDownList() {
$mysqli = mysqli_connect("host", "un", "pw", "db");
$dbname = 'database';
$sql = "SHOW TABLES FROM $dbname";
$result = mysqli_query($mysqli, $sql);
echo "<select name'selectName'>";
while ($row = mysqli_fetch_array($result)) {
$tempCounter = 0;
echo "<option value='".$row[$tempCounter]."'>".ucfirst($row[$tempCounter])."</option<br/>";
}
echo "</select>";
}

[/code]


This would work if you had a table for each country name. I'm not sure if I'm understanding your question right. Are you trying to use Ajax methods to get the dropdown to update? Even with Ajax you will still need PHP to access the DB.
Copy linkTweet thisAlerts:
@justice2authorSep 24.2009 — let me ask again. I have this dropdown lists that are populate from an external file called countryCityList.php where i have array from each country and i want to populate this list from that array only that I want this array to have the data from database. Tha data are from a table called members where i have country region and city.

This are the lists:

CODE:

<form id="form1" name="form1" method="post" action="registration2.php">

<table width="100%" border="0" cellpadding="6" cellspacing="20">

<tr>

<td><div align="right">

<label for="country">Your Country</label>

</div></td>

<td><div align="left">

<select style="width: 15em" name="country" id="country" onchange="setStates();">
<option selected="selected">Select your Country</option>
<option value="Germany">Germany</option>
<option value="Morocco">Morocco</option>
<option value="United Kingdom">United Kingdom</option>
</select>
</div></td>
</tr>
<tr>
<td><div align="right">
<label for="label">Your Region</label>
</div></td>
<td>
<div align="left">

<select style="width: 15em" name="region" id="region" onchange="setCities();">
<option selected="selected">Select your Region</option>
</select>
</div></td>
</tr>
<tr>
<td><div align="right">
<label for="city">Your City</label>
</div></td>
<td><div align="left">

<select style="width: 15em" name="city" id="city">
</select>
</div></td>


And this the external file where i want to have the arrays from the database if this could happen:

CODE:

var states = new Array();


states['Germany'] = new Array('Bayern','Berlin','Hamburg');

states['Morocco'] = new Array('Casablanca','Doukkala Abda','Guelmin');

states['United Kingdom'] = new Array('England','Scotland','Wales','Northern Ireland');


// City lists

var cities = new Array();

cities['Germany'] = new Array();

cities['Germany']['Bayern'] = new Array('Ainring');

cities['Germany']['Berlin'] = new Array('Berlin');

cities['Germany']['Hamburg'] = new Array('Hamburg');

cities['Morocco'] = new Array();

cities['Morocco']['Casablanca'] = new Array('ad-Dar-al-Baida');

cities['Morocco']['Doukkala Abda'] = new Array('al-Jadidah');

cities['Morocco']['Guelmin'] = new Array('Gulimim');

cities['United Kingdom'] = new Array();

cities['United Kingdom']['England'] = new Array('Abingdon');

cities['United Kingdom']['Scotland'] = new Array('Alford');

cities['United Kingdom']['Wales'] = new Array('Maesteg');

cities['United Kingdom']['Northern Ireland'] = new Array('Coleraine');

function setStates() {

cntrySel = document.getElementById('country');

stateList = states[cntrySel.value];

changeSelect('region', stateList, stateList);

setCities();

}

function setCities() {

cntrySel = document.getElementById('country');

stateSel = document.getElementById('region');

if (typeof(cities[cntrySel.value]) == 'undefined') {

cityList = new Array('<Select your city>');

}

else {

cityList = cities[cntrySel.value][stateSel.value];

}

changeSelect('city', cityList, cityList);

}

function changeSelect(fieldID, newOptions, newValues) {

selectField = document.getElementById(fieldID);

selectField.options.length = 0;

// if (typeof(newOptions) == 'undefined') {

if (fieldID == 'region') {

selectField.options[0] = new Option("<Select your region>", null);

}

if (fieldID == 'city') {

selectField.options[0] = new Option("<Select your city>", null);

}

// }

// else {

if (typeof(newOptions) != 'undefined') {

for (i=0; i<newOptions.length; i++) {

selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);

}

}

// }



}



function addLoadEvent(func) {

var oldonload = window.onload;

if (typeof window.onload != 'function') {

window.onload = func;

} else {

window.onload = function() {

if (oldonload) {

oldonload();

}

func();

}

}

}



addLoadEvent(function() {

setStates();

});



Please help me if you can.

Regards!
Copy linkTweet thisAlerts:
@BalistikBillSep 24.2009 — Well, PHP and Javascript don't go together. As far as I know you can't access a database with javascript, it's possible I'm wrong on this though. From my knowledge you would not be able to accomplish what you are asking because you need to have the PHP access the database. If someone else has a way to do this please reply on this thread so I may learn as well.

Thanks.
Copy linkTweet thisAlerts:
@justice2authorSep 24.2009 — Ok. Thanks for this reply. Well if i am connecting to database and extract data like this:

Code:

<?php

$sql="SELECT country FROM members";

$result =mysql_query($sql);

while ($country=mysql_fetch_assoc($result)){

?>

<option value ="<?php echo $country['id'] ?>" >

<?php echo $country['country'] ?>

</option>

<?php } ?>

how can i put that data to this array

Code:

var states = new Array();

states['Germany'] = new Array('Bayern','Berlin','Hamburg');

states['Morocco'] = new Array('Casablanca','Doukkala Abda','Guelmin');

states['United Kingdom'] = new Array('England','Scotland','Wales','Northern Ireland');

Of course I want to get rid of this long script and get this data from above from mysql database.

Please let me know if you understand what i say and please help me if you can. I really need to now this.
Copy linkTweet thisAlerts:
@justice2authorSep 24.2009 — I am searching for this from 2 days. And I didn't find anything. I will provide the final script when it's going to work completely.

Regards!
Copy linkTweet thisAlerts:
@justice2authorSep 26.2009 — Help! Please! I would really apreciate any help. I think I am not the only one who wants to find if something like this work.

What about ajax? I know that ajax can connect to a database but how can i extract that data into states array or the other one.

Thanks!
Copy linkTweet thisAlerts:
@JMRKERSep 26.2009 — Post a SAMPLE of the related 'country', 'region' and 'city' data entries from your database.

If I can see a sample, I'll try a solution, but I'm not into starting from scratch.
Copy linkTweet thisAlerts:
@justice2authorSep 26.2009 — In my database are all the country region and cities and the script I put it here all. All I want is that these array from .js file to be gone and to have arrays that extract data from database. database is selectstates, table is members and then are country,region and city... My first try was to pass php array from query to this new java script array but it didn't work and I delete everything.

Look for an example here:

postcrossing(dot)com(slash)signup

That form extracts all from database in that lists.

That is what I want but I need to have this javascript function to change the region when the first choice is made and then the to change the third when the second chance is made.

Thanks a lot for helping me and for response.
Copy linkTweet thisAlerts:
@ebarOct 30.2009 — yes javascript and php can be used together. php to do the database(SERVER) side commands and javascript to the page(CLIENT-SIDE ) commands. Its getting the two to work together that you need to do.

I'm trying to do the same thing... I have 5 sites that need the same thing. When i get it working i will post...
Copy linkTweet thisAlerts:
@ebarOct 30.2009 — <i>
</i>&lt;SCRIPT language=JavaScript&gt;
function reload(form)
{
var val=form.state_id.options[form.state_id.options.selectedIndex].value;
//var cid=form.clubid.value;
self.location='statetest2.php' + '?state_id=' + val ;
}
&lt;/script&gt;
[code=php]if(isset($_GET['state_id'])and strlen($_GET['state_id']) > 0){
$state_id = $_GET['state_id'];

echo '<select style="width: 15em" name="state_id" id="state_id" onchange="reload(this.form)">';

$statesql = "SELECT * FROM ebar_state ";
$stateres = mysql_query($statesql);
if ($stateres) {
while ($state = mysql_fetch_assoc($stateres) ) {
if ($state_id == $state['id']) {
echo '<option value="'.$state['id'].'" selected="selected">'.$state['state'].'</option>';
} else {
echo '<option value="'.$state['id'].'">'.$state['state'].'</option>';
}
}
}
echo '</select>';
echo '<select style="width: 15em" name="county" id="county">';
$cquery = mysql_query("SELECT * FROM ebar_county WHERE state_id ='".$state_id."' ORDER BY county");
if($cquery) {
while ($co = mysql_fetch_assoc($cquery) ) {
echo '<option value="'.$co['id'].'">'.$co['county'].'</option>';
}
} else {
echo 'umm no.' .mysql_error();
}
} else {
echo '<select style="width: 15em" name="state_id" id="state_id" onchange="reload(this.form)">';
$statesql = "SELECT * FROM ebar_state ";
$stateres = mysql_query($statesql);
if ($stateres) {
while ($state = mysql_fetch_assoc($stateres) ) {
echo '<option value="'.$state['id'].'">'.$state['state'].'</option>';
}
}
echo '</select>';
}[/code]
Copy linkTweet thisAlerts:
@000zeroOct 30.2009 — I think the easiest way to do what you want is to use php to populate the dropdown list when ur page loads up.

[code=php]
// connect to mysql
// execute your query
echo "<SELECT id="myDropDown">"
while ($row = mysql_fetch_row($your_query_results) {
echo "<OPTION>{$row[0]}</OPTION>"
}
echo "</SELECT>"
[/code]


and then in your javascript code do the following
[CODE]
var mySelectElement = document.getElementById("myDropDown");
var myListOfOptions = mySelectElement.getElementsByTagName("OPTION");
[/CODE]


thus you will have a list of all your drop down options that originally came from your database.

hope this helps
×

Success!

Help @justice2 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...