Cascade Dropdown List Using Jquery/Php

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



Leave a reply



Submit