Multiple dropdown with jquery ajax and php

by  
Share:
Multiple dropdown with jquery ajax and php

Filtering results or providing option to users based on some criteria is one of the most sought after thing in web development. User friendliness is the key, So in this tutorial I am going to explain how can you create multiple drop down with jquery ajax and php for filtering options based on some criteria.

View Demo

Multiple drop downs: what will this script do?

Let’s take a situation where a user submits a form, he has to fill up his country, state and city but state must be dependent on the selected country and so is the city which depends on the state. So this script provides the solution for this problem.

Setup your database first. Create three tables viz. country, state, city.

Below is the sql for creating country table in mysql.

CREATE TABLE IF NOT EXISTS `tbl_country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `tbl_country` (`id`, `country_name`) VALUES
(1, 'India'),
(2, 'USA'),
(3, 'Australia');

Now create state table. In the state table add a field named country_id so you can make relation between both the table.
CREATE TABLE IF NOT EXISTS `tbl_state` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `state_name` varchar(255) NOT NULL,
  `country_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

INSERT INTO `tbl_state` (`id`, `state_name`, `country_id`) VALUES
(1, 'West Bengal', 1),
(2, 'Rajasthan', 1),
(3, 'Himachal Pradesh', 1),
(4, 'Maharashtra ', 1),
(5, 'Victoria', 3),
(6, 'Western Australia', 3),
(7, 'Queensland', 3),
(8, 'South Australia', 3),
(10, 'Tasmania', 3),
(11, 'Alaska', 2),
(12, 'California', 2),
(13, 'New York', 2),
(14, 'Florida', 2),
(15, 'Texas', 2),
(16, 'Arizona', 2),
(17, 'Ohio', 2),
(18, 'Mississippi', 2);

And finally create the city table and just like state table create a field named state_id to manage the relation between the state and city tables.
CREATE TABLE IF NOT EXISTS `tbl_city` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `city_name` varchar(255) NOT NULL,
  `state_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;

INSERT INTO `tbl_city` (`id`, `city_name`, `state_id`) VALUES
(1, 'Kolkata', 1),
(2, 'Asansol', 1),
(3, 'Siliguri', 1),
(4, 'Durgapur', 1),
(5, 'Bardhaman', 1),
(6, 'Dankuni', 1),
(7, 'Ajmer', 2),
(8, 'Bikaner', 2),
(9, 'Jaipur', 2),
(10, 'Udaipur', 2),
(11, 'Shimla', 3),
(12, 'Mumbai ', 4),
(13, 'Pune', 4),
(14, 'Nagpur', 4),
(15, 'Thane', 4),
(16, 'Solapur', 4),
(17, 'Bhiwandi', 4),
(18, 'Amravati', 4),
(19, 'Nashik', 4),
(20, 'Melbourne', 5),
(21, 'Geelong', 5),
(22, 'Kalgoorlie', 6),
(23, 'Rockingham', 6),
(24, 'Bundaberg', 7),
(25, 'Caloundra', 7),
(26, 'Townsville', 7),
(27, 'Mount Isa', 7),
(28, 'Mount Barker', 8),
(29, 'Victor Harbor', 8),
(30, 'Hobart ', 10),
(31, 'Launceston', 10),
(32, 'Sitka', 11),
(33, 'Juneau', 11),
(34, 'Wrangell', 11),
(35, 'Anchorage', 11),
(36, 'Los Angeles', 12),
(37, 'San Diego', 12),
(38, 'New York City', 13),
(39, 'Rome', 13),
(40, 'North Port', 14),
(41, 'Jacksonville', 14),
(42, 'Bunnell', 14),
(43, 'Tampa', 14),
(44, 'Beaumont', 15),
(45, 'Waco', 15),
(46, 'Marana', 16),
(47, 'Eloy', 16),
(48, 'Cleveland', 17),
(49, 'Cincinnati', 17),
(50, 'Jackson', 18);

Database set. Start coding!

Create a php file name configure.php that will have the database connection code.

<?php
// display all error except deprecated and notice  
error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );
// turn on output buffering 
ob_start();

define('DB_DRIVER', 'mysql');
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "sampletest");

// basic options for PDO 
$dboptions = array(
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

//connect with the server
try {
    $DB = new PDO(DB_DRIVER . ':host=' . DB_HOST . ';dbname=' . DB_DATABASE, DB_USER, DB_PASSWORD, $dboptions);
} catch (Exception $ex) {
    echo($ex->getMessage());
    die;
}

?>

In the landing page display all the countries in a drop down. Bind a function showState() with the drop down onChange event so you can use it in jquery ajax call.
<?php
$sql = "SELECT * FROM tbl_country ORDER BY country_name";
try {
	$stmt = $DB->prepare($sql);
	$stmt->execute();
	$results = $stmt->fetchAll();
} catch (Exception $ex) {
	echo($ex->getMessage());
}
?>
<label>Country:
	<select name="country" onChange="showState(this);">
		<option value="">Please Select</option>
		<?php foreach ($results as $rs) { ?>
			<option value="<?php echo $rs["id"]; ?>"><?php echo $rs["country_name"]; ?></option>
		<?php } ?>
	</select>
</label>

Create two div container where you want both your state and city drop down to be displayed.
<!-- This will hold state dropdown -->
<div id="output1"></div> 

<!-- This will hold city dropdown -->
<div id="output2"></div>

Write the jquery code inside the function showState(). Add an ajax function that will call fetch_state.php which will return the drop down with the results based on the country.
<script>
function showState(sel) {
	var country_id = sel.options[sel.selectedIndex].value;  
	$("#output1").html( "" );
	$("#output2").html( "" );
	if (country_id.length > 0 ) { 

	 $.ajax({
			type: "POST",
			url: "fetch_state.php",
			data: "country_id="+country_id,
			cache: false,
			beforeSend: function () { 
				$('#output1').html('<img src="loader.gif" alt="" width="24" height="24">');
			},
			success: function(html) {    
				$("#output1").html( html );
			}
		});
	} 
}
</script>

In the page fetch_state.php assign the country_id in a variable and then execute a query based on that country id.
<?php
$country_id = ($_REQUEST["country_id"] <> "") ? trim($_REQUEST["country_id"]) : "";
if ($country_id <> "") {
    $sql = "SELECT * FROM tbl_state WHERE country_id = :cid ORDER BY state_name";
    try {
        $stmt = $DB->prepare($sql);
        $stmt->bindValue(":cid", trim($country_id));
        $stmt->execute();
        $results = $stmt->fetchAll();
    } catch (Exception $ex) {
        echo($ex->getMessage());
    }
    if (count($results) > 0) {
        ?>
        <label>State: 
            <select name="state" onchange="showCity(this);">
                <option value="">Please Select</option>
                <?php foreach ($results as $rs) { ?>
                    <option value="<?php echo $rs["id"]; ?>"><?php echo $rs["state_name"]; ?></option>
                <?php } ?>
            </select>
        </label>
        <?php
    }
}
?>

Just repeat the above two step for fetching city, write the javascript/jquery code for fetching the city drop down via ajax, and again the php file that will return the city drop down.
<script>
function showCity(sel) {
	var state_id = sel.options[sel.selectedIndex].value;  
	if (state_id.length > 0 ) { 
	 $.ajax({
			type: "POST",
			url: "fetch_city.php",
			data: "state_id="+state_id,
			cache: false,
			beforeSend: function () { 
				$('#output2').html('<img src="loader.gif" alt="" width="24" height="24">');
			},
			success: function(html) {    
				$("#output2").html( html );
			}
		});
	}
}
</script>

The file fetch_city.php that will return the city drop down.
<?php
$state_id = ($_REQUEST["state_id"] <> "") ? trim($_REQUEST["state_id"]) : "";
if ($state_id <> "") {
    $sql = "SELECT * FROM tbl_city WHERE state_id = :sid ORDER BY city_name";
    try {
        $stmt = $DB->prepare($sql);
        $stmt->bindValue(":sid", trim($state_id));
        $stmt->execute();
        $results = $stmt->fetchAll();
    } catch (Exception $ex) {
        echo($ex->getMessage());
    }
     if (count($results) > 0) {
        
        ?>
        <label>City: 
            <select name="city" name="box">
                <option value="">Please Select</option>
                <?php foreach ($results as $rs) { ?>
                    <option value="<?php echo $rs["id"]; ?>"><?php echo $rs["city_name"]; ?></option>
                <?php } ?>
            </select>
        </label>
        <?php
    }
}
?>

View Demo
Download

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Comet on

Hi

This is a pretty good tutorial.

I have a question, how can I use city_id (after selecting third drop down) further on index.php

Reply
Shahrukh Khan on

Hi. It’s quite simple. just like create a div with an unique id like say then bind a function say showMore(); for city dropdown box(onchange) and call and ajax function just the way the state and city is called. Hope this helps 🙂

Reply
Comet on

See I have these 3 dropdown then a text box. Now when I will be submitting the form, it will go to ‘action’ page there I will be having the value entered in the text box like $x=$_POST[‘name_of_text_box’];
but not the value of selected last drop-down for further SQL query.
How can I get that selected drop-down value can you let me know?

rohit on

how i can sort and filter things like amazaon and flipcart.

Shahrukh Khan on

You have to do that on server side.

Neelam on

hii,
I have a html dropdown(for selecting products)where i am fetching option values by calling an API .As a single vendor can sell multiple products i am appending dropdown fiels using jquery so as to select products and append as many required.
But my dropdown values are not coming from api when i am appending dropdown field by clicking Add button.Can you help me???

Shahrukh Khan on

is your API working when you call it standalone?

TK on

Great Tutorial. I have two questions. Is it possible to have all 3 drop downs show at the same time? instead of showing one drop down at a time? also is it possible to show all the results and then filter them out as selections are made?

Reply
Shahrukh Khan on

yes, it’s possible you can put static 3 dropdown all at once, but maintain their name and ids as it is..for the second question it can be done too by filtering results by values placing them in a hidden div and calling them as the selections are made.. but that is not a correct flow according to me as it has a lot of work overhead. It’s quite simpler this way.. “Why make things complex when they can be done the easier way.” take care

Reply
Haider on

hi shahrukh bt you didn’t define city and state in index.php

Reply
Shahrukh Khan on

It’s called using ajax.

Reply
ema on

hello .. thank you very much for this nice tutorial , I realy I need this code badly, I wonder if you can help me use the $country_id and $city_id and $state_id that the user had select from the menu in database operation like insertion and update and so on ….. thanks alot

Reply
Shahrukh Khan on

if you need some tutorial regarding that. you can send me using “Request a tutorial” section in the menu bar. Please provide me with detail what you want. I will surely help u.

Reply
deepak on

i wanna full code of multiple dropdown list using jquery ajax.

Reply
Shahrukh Khan on

download link is given just after the end of article..

Reply
Manish Kumar on

Hi there. very nice tutes..
can u tell me, how whole process is works. ??

Reply
Shahrukh Khan on

the whole process is ajax based on fetching data from database using html dropdown value. you can download the source code and check it.

Reply
Manish Prajapati on

Hello Shahrukh Khan , First of all. this is very nice tutorial.
i like it ur way of code. i am new to ajax and jquery. so what i want that, when country , states, city were selected after that two input box will apear as first name and last name. can u do me favor this. ?

i want like this. by ajax .

Reply
Shahrukh Khan on

its quite simple.. just on the end of showcity function after the line
$(“#output2″).html( html ); you add two text field

$(”).appendTo( “#output2” );

Reply
Art Reserve Bank on

Great simple tutorial – Thanks!

I like to use these multiple dropdowns to edit existing data.

Having the country set as ‘selected’ is of course no problem. But is it possible to have states and cities shown with options marked as selected *without* changing the country?
In other words: how to set default ‘selected’ items?

Reply
Shahrukh Khan on

for that case you have to tweak the code, first replace the code in in their dropdown from showState(this); showCity(this) to

showState(this.value); showCity(this.value)

next set the variable
var country_id = sel.options[sel.selectedIndex].value;
var country_id = sel;

var state_id = sel.options[sel.selectedIndex].value;
var state_id = sel;

now final part is..
suppose u make india as selected.. india ha say id = 1
in the bottom of page write

// pass valid country id and state id in the function.
showState(1);
showCity(5);

Reply
Art Reserve Bank on

Thanx for prompt reply.
I changed the code accordingliy but it doesn’t seem to work. I am not sure but looks like the two variables (like ‘country_id’ in function showState) are conflicting. Have you tried it?

Shahrukh Khan on

Please try to debug the error. there must be some syntax mistake. I have told u the logic what needed to be done. I am sure it will be some silly mistake.. Try and let me know.

Art Reserve Bank on

Run debugger (but I am not very familiair with Jscript). After altering onchange action showState(this) to showState(this.value) I get an error with the line:

country_id = sel.options[sel.selectedIndex].value;

[error: undefined or empty reference]

Shahrukh Khan on

u need to call both state and city in the parent page at the bottom of page.. just above the tag

// add ur value
showState(1);
showCity(5);

Art Reserve Bank on

I understand. I want to show just Country and State.
I load page with default Country and default State both set by the record from database.

Page loads with correct country selected in Country dropdown.
function showState(sel) calls fetch_state.php which loads dropdown with the correct States of the selected Country. Great! But the default State is not selected. Dropdown States opens with the option “Please select”.
That’s what I mean that the function showState() should send an extra parameter (‘sel’ and ‘defaultstate_id’) to fetch_state.php in order to check which State should be marked as ‘selected’ in de Ajax-generated dropdown.

Shahrukh Khan on

I have email the working solution. Please check your inbox.

JCLover on

Can you send me the solution as well. I am getting the same issue.

Lily on

Please email me also the working solution.. im facing same problem

chandrasekhar pachari on

how to update the data using this did u get my intension. let me explain u

suppose i have inserted data like this into a table

insert into details(id,name,countyr_id,state_id,city_id) values(‘1′,’sekhar’,’1′,’2′,’1′);

i want to update this data using ur drop down how is it possible.

help me please………………. thanks

Reply
kher kirit on

this statment in (country_id=”+country_id,)
+country_id why use
plz help me

Reply
Shahrukh Khan on

that is the parameter that is been passed when u change the country.

Reply
lakhan on

hi i have 2 dropdown use first drown class and second dropdown student ,i insert dropdown value into database
the first dropdown value insert into databse but second dropdown not inserted intio database ..please rply fast

Reply
Shahrukh Khan on

Hi. Make sure your query is correct and proper values are passed when submitting the form.

Reply
Peter on

Please how do I get the value of the city_id and state_id….have to insert them into the database table…the only value I could get was country…I mean this:
$country = $_POST[‘country’];
$state = $_POST[‘state’];
$city = $_POST[‘city’];

The $_POST[‘state’] and $_POST[‘city’] are not holding any value at all…Please help

Reply
Shahrukh Khan on

make sure use use post method when u send value, also state and state must have value or visible when sending value.

Reply
Peter on

still trying to understand php can you please write out the codes

Rick on

I’m also having issues inserting state and city via POST. The thing is because the info is pulled from database via AJAX it doesn’t show up in the html so can’t be used by just using the select id. I’m not sure how to get the value of state or city so that it is available to insert in the database in my mysql/PDO database call

Shahrukh Khan on

Just make sure that the state and city dropdown is visible before you submit the form, that is how the value is passed from the form.

prabakar on

hi shahrukh,
very nice tutorial .
thanks

Reply
CB Singh on

Really useful. I just needed this for PIN code search script. I will implement it there

Reply
Chetan on

hi boss,
its really use full to me… thanks a lot…
but, there is another problem other than this,
i want to get activate 2 updated drop downs at a time… means if i select country as India it should show the both states and the city drop downs… how its possible plsss let me know with the code….

Thank you…

Reply
Shahrukh Khan on

on the event1 success just use this
$(“#output1”).show();
$(“#output2”).show();

Reply
Chetan on

Thanks a lot boss….. 🙂
If you don’t mind can I get the zip folder of the demo which you gave above…
i’m pleasing you for that…

Thank you…

Shahrukh Khan on

Just click the social link below the article to unlock the download zip file.

Saif Ansari on

Nice Tutorial, Working Fine.

Reply
Shahrukh Khan on

Thank you.

Reply
Pankaj on

Nice tutorial But, When I select the first comboBox I doesnt show the Second One..Please Help

Reply
Shahrukh Khan on

have you tried to debug your code.

Reply
GiaSqui on

Hi Shahrukh Khan and thanks for you tutorials.
I have the same problem of Pankaj. After I have selected the first dropdown, the second doesn’t appear.
I new in php jquery ajax and I don’t know if I have to installa something, such as jquery and/or ajax.
I have three file, first is configure.php, second is fetch_state.php and the last is fetch_city.php.
Where I wrong?
Best regards.

Reply
GiaSqui on

Hi Shahrukh Khan I have found the download and it works! Thanks a lot for the tutorial!

Reply
Shahrukh Khan on

Hi Gia. I guess you have some JavaScript problem. Make sure your jquery file is also ok. The ID of the dropdown is binded with the onchange event i.e. the functions which fires and ajax call to the php script. best of luck

Reply
GiaSqui on

Hi Shahrukh and thanks for your reply. Now it works! I’m trying to modify the code in order to achive my goal, that is the following: when I select the third dropdown, I need to launch a query on mysql based on the item selected in the previous three dropdown menu and retrieve one row only. How can I do it? Best regards.

Shahrukh Khan on

Create a function same as before accepts the value off three dropdown and fire and ajax request to the php page. and whatever the value is returned display it on the dropdown. The process of creating function and all are mentioned in the tutorial above.

GiaSqui on

Hi Shahrukh. Ok, but how I can create a function that accepts three values?
This is the function:

function showAttenuation(sel) {
var frequencyMHz = sel.options[sel.selectedIndex].value;
if (frequencyMHz.length > 0) {
$.ajax({
type: “POST”,
url: “fetch_attenuation.php”,
data: “frequencyMHz=” + frequencyMHz,
cache: false,
beforeSend: function() {
$(‘#output3’).html(”);
},
success: function(html) {
$(“#output3”).html(html);
}
});
} else {
$(“#output3”).html(“”);
}
}

I have to declare more “data” in the ajax? How I can do it?
Thanks and best regards.

Shahrukh Khan on

you need to accept values store in a variable and in this link below append it.
data: “frequencyMHz=” + frequencyMHz+”&variable2=value2&variable3=value3″

GiaSqui on

Ok, but why it does not work?!

I have in the index.php the following code:

……
function showAttenuation(selFreq, selCabTyp) {
var frequencyMHz = selFreq.options[selFreq.selectedIndex].value;
var selCabTyp = document.getElementById(“tipoCavo”);
var cableType = selCabTyp.options[selCabTyp.selectedIndex].value;
if (frequencyMHz.length > 0 & cableType.length > 0) {
$.ajax({
type: “POST”,
url: “fetch_attenuation.php”,
data: “frequencyMHz=” + frequencyMHz+ “cableType=” + cableType,
cache: false,
beforeSend: function() {
$(‘#output3’).html(”);
},
success: function(html) {
$(“#output3”).html(html);
}
});
} else {
$(“#output3”).html(“”);
}
}
……

while the fetch_attenuation.php is this:

<?php

require("configure.php");
$frequencyMHz = ($_REQUEST["frequencyMHz"] “”) ? trim($_REQUEST[“frequencyMHz”]) : “”;
$cableType = ($_REQUEST[“cableType”] “”) ? trim($_REQUEST[“cableType”]) : “”;

if ($frequencyMHz “”) {
//$sql = “SELECT attdB100m, attdB100ft, avgPwrkW FROM cable WHERE frequencyMHz = :freqid ORDER BY attdB100m”;
$sql = “SELECT * FROM `cable` WHERE cableType = :cabtypid AND frequencyMHz = :freqid ORDER BY attdB100m”;

try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(“:cabtypid”, trim($cableType));
$stmt->bindValue(“:freqid”, trim($frequencyMHz));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo($ex->getMessage());
}
if (count($results) > 0) {
?>
Attenuazione:

Please Select

<option value="”>

The three dropdown appear and works but the last query doesn’t go.
May you help me?
Thanks a lot.

Reply
Shahrukh Khan on

maybe you can send me the source code. so i can have a look at my free time.

Reply
GiaSqui on

Sure. May I have your email?

Reply
GiaSqui on

I have your email… and I have send the code. Hope you can help me.
Best regards.
G

Reply
narayan on

it is good…………. after clicking those dropdowns…… I want to add some images were i should add images? were i should give image references

Reply
narayan on

i want to add some images country wise………… how should i do plzz help me out

Reply
Germano on

Hi Khan

This tutorial is pretty good and useful. I kindly need a favor on how to sort data from other table using data from dependent dropdown. That means i will be able to sort all data from other table say ‘firstName’, ‘lastName’ and ‘phoneNumber’ with country,state and city selected from dropdown after clicking the sort button.

Regards.

Reply
Shahrukh Khan on

Hello Germano.
Concept is very similar for your problem. just create dropdown and send value via ajax call. In the php page then get those value you have passed and create a query based on that and make sql call. Rest are similar.
Eg. suppose you send value or want to sort with “firstname” send “?sort=fname” via ajax and in php page you have $sort = $_GET[“sort”];
Now just in your sql append/update
say you sql is $sql = “select * from table where 1”;
if ($sort == “fname”)
$extraSql = $sql.” ORDER BY firstname ASC “; (taking firstname is your column name)

hope this helps.

Reply
Ajay on

hello,
Nice tutorial but I am facing such a problem
SQLSTATE[HY000] [1045] Access denied for user ‘abcd’@’localhost’ (using password: NO)

Reply
Shahrukh Khan on

make sure your database username and password is correct

Reply
Germano on

Mr.Khan, thanks very much for your reply. Very helpful

Reply
John on

Many thanks for your wonderful tutorial. I use netbeans and have constructed all the tables in xampp and links as well as the index.php and the other php files. Sadly the construction of the ‘landing page’ which I think you mean the index page is not part of the integration that is easily comprehended. At least by me! I have looked at your css and html results in my browser and tried to understand what files or scripts you put here and there with little comprehension. I think it is the ‘integration’ linking and schematic outline of all elements of any project that poses the greatest challenge to most folks particularly when many ‘types’ of programing languages are used.
Would love to comprehend the integration more fully.
cheers,
John

Reply
Patrick on

Hi Shahrukh,
Very good and useful tutorial.
Could you use Json to retun values of each dropdown please ?
Thanks

Reply
Shahrukh Khan on

Yes that can be done too. In that case the json has to be parsed and put it in the dropdown.

Reply
Patrick on

Thank you
Have you got an example with Json please ?
Cheers

Reply
Tapas on

hey,friend sahrukh,just awesome tutorial…
But i want to show all filtered values like country_name, state_name,city_name as output in a single page….
then what i have to do? please help me out ,its so important to me. thanks in advance.

Reply
Tapas on

hey friend ,please help me.

Reply
pythias on

Hi Shahrukh,
Very nice and useful tutorial and thanks.
I have tried to connect it using sql server but i am unable to select the country, state and city.Please kindly help me on how to connect it using sql server which i have installed on my laptop

Reply
Shahrukh Khan on

If you are connecting using PHP PDO classes then its very easy. make sure you have msmsql extension/drivers in your php package.
PHP driver can be found here: https://msdn.microsoft.com/en-us/library/ff754357(v=sql.105).aspx
AND you can connect using this php code
$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");

Reply
Amarnath on

Hi shahrukh
Very nice and useful tutorial and thanks.
But can i use this code with single table like id,country,state,city?
So please how to use this with single table.

Reply
Christopher on

Nice demo, thanks very much, how I can echo the results of the select options please, instead of the id’s

Reply
Shahrukh Khan on

use console.log function

Reply
Christopher Astbury on

Hi Really nice example, that I have working, how can I echo the results onto a webpage, and also push those results into a database, not the ID’s but the actual names please

Reply
Anderson on

Good evening, I changed the “select” only for my bank to pursue other data and does not work, can you help me?

Reply
Anderson on

the last drop down not appear

Reply
naga on

hello sir ,

i’m inserting values to database with two dropdowns , got inserted .
and if i’ve again inserting values to database means the second dropdown must be checked if the same data is present in database dependent to first dropdown . how to do it in php mysqli using jquery???

plz help me sir

Reply
Shahrukh Khan on

when you post the data, check if $_POST[‘field1’] != $_POST[‘field2’]

Reply
PRAKASH on

This Same code is use for edit option ? or Not?.

Reply
Shahrukh Khan on

this is the front end.

Reply
PRADEEP on

Download link didn’t worry. Please send me the code

Reply
PRADEEP on

Sorry… Download link didn’t work…

Reply
Shahrukh Khan on

it is working fine. please try again

Reply
Tony on

Hi Shahrukh, I’ve seen almost all the comments people leave here and your article really rocks so thanks again.
My problem is that when I submit, its the indexes of the tables which are saved in the database. Please tell me how to fix it. Thanks again

Reply
Shahrukh Khan on

what index?

Reply
lina on

Thank you very much. I was curious if the drop down could be changed to a text field, so when the person starts typing their city, the drop down will appear instead while they’re typing to predict their city. or would this set up not work for that? THANK YOU!

Reply
Shahrukh Khan on

check chosen or select2 javascript plugin.

Reply
Pribadi on

How if i want to make this multiple dropdown without connection with database?
just query i declare in source code..

thx for your advice…

Reply
Shahrukh Khan on

you need to put in json file or simply set in php variables.

Reply
syed adeebulla on

Awesome tutorials

Reply
Lily on

your tutorials are so much helpful.. Thankyou so much for doing all this..

Reply
Shahrukh Khan on

you are welcome.

Reply
Chamroeun Tun on

Thank! this tutorial is helpful.

Reply
Max on

Hello great job same problem you think you can also send the file in which the countries states and cities are shown with * select one *

Reply
Shahrukh Khan on

I dont quite understand your issue?

Reply
Stuart on

Hi thanks for the tutorial. The correct variable is being passed to the Ajax file, but the 2nd dropdown isn’t populating. Is my query wrong for the 2nd dropdown? I’ll paste below:

query(“SELECT DISTINCT material FROM stones WHERE category = “.$_POST[‘category’].” ORDER BY material ASC”);

//Count total number of rows
$rowCount = $query->num_rows;

//Material option list
if($rowCount > 0){
echo ‘Select material’;
while($row = $query->fetch_assoc()){
echo ”.$row[‘material’].”;
}
}else{
echo ‘Material not available’;
}
}elseif(!empty($_POST[“material”])){
//Fetch all shape data
$query = $db->query(“SELECT DISTINCT shape FROM stones WHERE material = “.$_POST[‘material’].” ORDER BY shape ASC”);

//Count total number of rows
$rowCount = $query->num_rows;

//Shape option list
if($rowCount > 0){
echo ‘Select shape’;
while($row = $query->fetch_assoc()){
echo ”.$row[‘shape’].”;
}
}else{
echo ‘Shape not available’;
}
}
?>

Reply
Arturo Claro on

The script runs perfect on php 5.6.30 nevertheless, when I upgrade to php 7.1.1 it gives me the following:
Fatal error: Uncaught Error: Undefined class constant ‘MYSQL_ATTR_INIT_COMMAND’ in C:\AppServ\www\tsg\configure.php:26 Stack trace: #0 C:\AppServ\www\tsg\index.php(10): require() #1 {main} thrown in C:\AppServ\www\tsg\configure.php on line 26

Reply
Shoeb on

Hi,

Everything is fine but I have a query I want to put a submit button after city is selected and then display more results on the page related to the details of the selected city like the selected city’s weather, pincodes, population etc. Could u plz help me out?

Reply
Shahrukh Khan on

Hi. you need to run AJAX call and display the data, get started my from code most of the function to send and get data is already there, just replicate the functions and use as per your requirements.

Reply
Victor Adegbite on

Hi,
Nice one.
How do I make it go to the page when the final choice is made from the drop-down menu?
Thanks

Reply
Shahrukh Khan on

use window location javascript code.

Reply
Rasa on

Hello, It’s all ok. How I could save what I choose, because it’s new for me

Reply
Umair Temuri on

Hi there Shahrukh,

Good posts you have here. It’s hard to find good quality sites like yours these days.
I honestly appreciate people like you! Take care!

Reply
Brienen on

Hi,

How can i use the chosen values from the 3 dropdowns further on in php ?
I dont know how to pass the 3 jquery variables to php because i want to do an update in another table with the chosen values :

UPDATE world
SET country_name=:country_name, state_name=:state_name, city_name=:city_name
WHERE country_id=:id;

Thanks

Reply
Victor Adegbite on

Hi,
Nice one my friend. Please how do make the database open a page after selection?

Reply
Victor Adegbite on

Hi,
Can someone help me with the location javascript code to make the database open a page after the search?
Help needed urgently please.

Reply
Victor Adegbite on

Hi Hassan,

What happens if I want to have 4 or 5 database instead of the 3 you used.
What can I do?

Reply
Hasan on

It is similar to it, just use the same logic.

Reply
Victor Adegbite on

Thanks so much.
Finally, I need your help on how to window location javascript code to your
code such that any selection made will be opened.

Thank you once again.

From Victor

Hasan on

Email me, will try to help you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.