How to make a Cascading Drop Down List in PHP using jQuery
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
cascading dropdown jquery ajax php
first, change your mysql_escape_string
to mysqli_escape_string
$state = trim(mysqli_escape_string($con, $_POST["state"]));
and then wrap your state
in quotes
$sql = "SELECT DISTINCT city FROM tbl_zip WHERE state = '".$state ."' ORDER BY city";
also, take the <script>
block out of fetch_state.php
and just have it in index.php
with the other <script>
block
Issue with JQuery Country and State cascading dropdown showing all states until country dropdown changed
Refreshing the country
list should be as easy as calling jQuery('select[name="country"]').trigger('change')
after setting up the listener, the only caveat is that you'll lose the current state
selection, since you'll be emptying and repopulating it. You can get around that by saving its value first and check if it's present in the new state list.
jQuery(document).ready(function ()
{
// Cache the jQuery objects, don't look them up in each access
var $countrySelector = jQuery('select[name="country"]');
var $stateSelector = jQuery('select[name="state"]');
$countrySelector.on('change',function(){
var countryID = $countrySelector.val();
var stateID = $stateSelector.val();
if(countryID)
{
jQuery.ajax({
url : '/getStates/' +countryID,
type : "GET",
dataType : "json",
success:function(data)
{
$stateSelector.empty();
jQuery.each(data, function(key,value){
// Check if current element matches previous selection
$stateSelector.append(
`<option value="${key}"${key == stateID ? ' selected' : ''}>${value}</option>`
);
});
}
});
}
else
{
$stateSelector.empty();
}
});
// After document is loaded and handler set up, fire the handler
$countrySelector.trigger('change');
});
Further reference for template literals.
Cascading Dropdown using JQuery/AJAX return undefined results even though I can see the array
When you remove .suiteId
from item
and you get [object Object],[object Object],[object Object]
in option it means your item
is still an array and you are not looping your data
correctly, and is also reason behind undefined
.
Because you did not post your exact data
format you are getting as response in order for us to see exact structure you can as fast fix add another loop:
$.each(data, function(i, item) {
item.forEach(opt => {
$("#SuiteId").append(`<option value="${opt.suiteId}">${opt.suiteNo}</option>`);
return (i !== "result")
})
});
and once again I am saying you have one for each to many, you need just one, but we need to see exact output not just contents of data
.
How to populate a cascading Dropdown with JQuery
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
Related Topics
Pdo Were Rows Affected During Execute Statement
Simple PHP Echo Code Not Working
PHP How to Remove Last Part of a Path
File_Get_Contents Returns Empty String
How to Search Array for Multiple Values in PHP
Sending/Displaying a Base64 Encoded Image
How to Pass an Array of Pdo Parameters Yet Still Specify Their Types
What Means Call to a Member Function on Boolean and How to Fix
Convert PHP Array String into an Array
Using Return in Ternary Operator
Multiple Http Get Parameters with the Same Identifier
Checking Browser's Language by PHP
Pcre Regular Expression Overlapping Matches
What's the Best Way to Create a Single-File Upload Form Using PHP