Dynamic selection how fetch 'Specific Cities of Specific State of Specific Country'? - php

I have the following setup of a dynamic select options for Country, State and City using php and jquery ajax.
But the problem with this setup is, if two or more of the states have the same name, all of their associated cities become the output irrespective of country.
Like the image below (please imagine Canada has a state named California for the sake of this example):
How can I solve this problem, that is how can I get the output of Cities of State California of Country USA?
These are the sections I guess I need to improve. I have been trying a few methods but none of them is working. So I'll really appreciate any help.
The ajax:
$('.action').change(function() {
if ($(this).val() != '') {
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "country") {
result = 'state';
} else {
result = 'city';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {
action: action,
query: query
},
success: function(data) {
$('#' + result).html(data);
}
})
}
});
And the php query I have tried:
$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output.= '<option value="">Select City</option>';
while ($row = mysqli_fetch_array($result))
{
$output.= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
}
This is the full code in case you need to have a look:
index.php
<?php
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$country .= '<option value="' . $row["country"] . '">' . $row["country"] . '</option>';
}
?>
<select name="country" id="country" class="form-control action">
<option value="">Select Country</option>
<?php echo $country; ?>
</select>
<select name="state" id="state" class="form-control action">
<option value="">Select State</option>
</select>
<select name="city" id="city" class="form-control">
<option value="">Select City</option>
</select>
<script>
$(document).ready(function () {
$('.action').change(function () {
if ($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "country")
{
result = 'state';
} else
{
result = 'city';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {action: action, query: query},
success: function (data) {
$('#' + result).html(data);
}
})
}
});
});
</script>
And the fetch.php
<?php
if (isset($_POST["action"])) {
$output = '';
if ($_POST["action"] == "country") {
$query = "SELECT state FROM country_state_city WHERE country = '" . $_POST["query"] . "' GROUP BY state";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select State</option>';
while ($row = mysqli_fetch_array($result)) {
$output .= '<option value="' . $row["state"] . '">' . $row["state"] . '</option>';
}
}
if ($_POST["action"] == "state") {
$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select City</option>';
while ($row = mysqli_fetch_array($result)) {
$output .= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
}
}
echo $output;
}
?>

You need populate next selects for all filled selects before and build right query for data.
#Example for populate CITY you need to know which are COUNTRY and STATE was selected.
PHP
if(isset($_POST['country']) && $_POST['country'] != ''
&& (!isset($_POST['state']) || $_POST['state'] == '') {
// return STATES for selected COUNTRY
$sql = "SELECT country, state FROM tbl WHERE country = {postCountry}";
}
else if(isset($_POST['country']) && $_POST['country'] != ''
&& isset($_POST['state']) && $_POST['state'] == '') {
// return CITIES for selected COUNTRY and STATE
$sql = "SELECT country, state, city FROM tbl WHERE country = {postCountry} AND state = {postState}";
}
This query
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
can be changed to DISTINCT
$query = "SELECT DISTINCT country FROM country_state_city ORDER BY country ASC";
JQUERY
Is good approach to wrap data into form because it provides easy work with form elements like selects.
$('.action').change(function() {
var formValues = $(this).closest('form').serialize();
$.ajax({
url: "fetch.php",
method: "POST",
data: formValues,
success: function (data) {
$('#' + result).html(data);
}
});
});
You can check DevTools Console on change and XHR request in Network in demo which values are sent in request to PHP.
DEMO JQUERY
Hope this help.
Happy coding

Related

Fill Drop down On select Of Drop down

how to fill dropdown values on selection of multiple dropdown.for example i have following Dropdown list.
On select of second dropdown i wants to fill Third Dropdown With Single selection How can i do. ?
My current code for this is as follow.
//CALL FOR SECOND DROPDOWN
$(document).ready(function(){
$('#select4').on('change',function(){
var subcatgoryId = $(this).val();
console.log(subcatgoryId);
if(subcatgoryId){
$.ajax({
type:'POST',
url:'ajax_load_specification.php',
data:{subcatgoryId: subcatgoryId},
success:function(html){
alert(html);
//$('#select5').html(html);
//$('#loading1').css("display","none")
},
error: function (jqXHR, exception) {
alert("Got Some Errore");
}
});
}else{
$('#select5').html('<option value="">Select Category first</option>');
}
});
});
and php code is as follow
if(isset($_POST["subcatgoryId"]) )
{
$subcategory = explode(',', $_POST["subcatgoryId"]);
print_r($_POST["subcatgoryId"]);
foreach ($subcategory as $key => $value)
{
echo $key;
echo "<br>";
$query1 = "SELECT * FROM m_subcategory WHERE id = ".$item." ";
$query1 = $conn->query($query1);
$query1 = $query1->fetch_object();
if($query1){
$id = $query1->id;
$name = $query1->name;
echo '<option value="'.$id.'">'.$name.'</option>';
}else{
echo '<option value="">We Get Empty Category</option>';
}
}
}
Just Use For Loop And it starts working
if(isset($_POST["subcatgoryId"]) )
{
$subcategory = $_POST["subcatgoryId"];
$len=count($subcategory);
for ($i=0; $i < $len; $i++) {
$query1 = "SELECT * FROM m_subcategory WHERE id = ".$subcategory[$i]." ";
$query1 = $conn->query($query1);
$query1 = $query1->fetch_object();
if($query1){
$id = $query1->id;
$name = $query1->name;
echo '<option value="'.$id.'">'.$name.'</option>';
}else{
echo '<option value="">We Get Empty Category</option>';
}
}
}

ajax search displaying id onclicking the name

this code displays the name as i type, as i type it gives suggestion of names and when clicked on it it displays the result in the textbox.but i want to display the id related to that name from database when i clicked on that name from the dropdown option. please help
<input type="text" name="st_id" id="st_id" ><div id="txtHint" style="position: absolute; width:390px ;"></div>
ajax code:
$(document).ready(function () {
$("#st_id").keyup(function () {
var search = $(this).val();
if (search != '') {
$.ajax({
type: "POST",
url: "ajaxcode.php",
data: {search: search},
success: function (data) {
$("#txtHint").fadeIn();
$("#txtHint").html(data);
}
});
}
});
});
php code
<?php
if (isset($_POST["search"])) {
$display = '';
$q = $_POST["search"];
$stmt = $DBconnect->prepare("SELECT * FROM table1 WHERE First_name LIKE :sh ");
$stmt->bindValue(':sh', '' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$display = '<ul class="list-unstyled">';
foreach ($stmt as $row) {
if ($row) {
$display .= '<li>' . $row["First_name"] . ' ' . $row["Middle_name"] . ' ' . $row["Last_name"] . '</li>';
} else {
$display .= '<li>name not found</li>';
}
}
$display .= '</ul>';
echo $display;
}
?>
Most naive way I can come up with is adding an id to the top ul
<ul id="name_suggestion" class="list-unstyled">
and the id to the <li> tag with a data- attr
$display .= '<li data-user-id = '. $row["id"] . '>'.$row["First_name"].' '.$row["Middle_name"].' '.$row["Last_name"].'</li>';
Then add an a click listener to the li:
$('#name_suggestion li').on('click', function(e){
let val = $(this).attr('data-user-id');
$('#st_id').val(val);
});

Mysql select box with jquery post

i have a country state city database that displaying in select boxes and everything is working fine. What i want when state select box selected to display city results in a div or another element. When select box defined for city results there is no problem but if i use div gives the error message
Notice: Undefined index: country in C:\wamp\www\list\post.php on line 3.
here is my codes, thanks.
post.php
include("connect.php");
$country = $_POST['country'];
$query = mysqli_query($connect, "select * from state where country_id='$country'");
while( $list = mysqli_fetch_array( $query ) ) {
echo '<option value=' . $list["id"]. '>' . $list["state_name"] . '</option>';
}
$state = $_POST['state'];
$query = mysqli_query($connect, "select * from city where state_id='$state'");
while( $list = mysqli_fetch_array( $query ) ) {
echo $list["city_name"];
}
jquery codes
$( "#countries" ).change( function(){
$("#states").empty();
var val = $(this).val();
$.post("post.php", {country:val}, function(a) {
$("#states").append(a);
});
});
$( "#states" ).change( function(){
$("#cities").empty();
var val = $(this).val();
$.post("post.php", {state:val}, function(a) {
$("#cities").append(a);
});
});
index.php
<?php include("connect.php"); ?>
<select id="countries">
<option>select</option>
<?php
$query = mysqli_query($connect, 'select * from country');
while( $list = mysqli_fetch_array( $query ) ) {
echo '<option value=' . $list["id"]. '>' . $list["country_name"] . '</option>';
}
?>
</select>
<select id="states">
<option>select</option>
</select>
<div id="cities"></div>
The script needs to cheeck whether it was called with the country or state parameter, and perform the appropriate query. And the code for returning the cities needs to put them in <option>, just like returning states does.
include("connect.php");
if (isset($_POST['country'])) {
$country = mysqli_real_escape_string($connect, $_POST['country']);
$query = mysqli_query($connect, "select * from state where country_id='$country'");
while( $list = mysqli_fetch_array( $query ) ) {
echo '<option value=' . $list["id"]. '>' . $list["state_name"] . '</option>';
}
elseif (isset($_POST['state'])) {
$state = mysqli_real_escape_string($connect, $_POST['state']);
$query = mysqli_query($connect, "select * from city where state_id='$state'");
while( $list = mysqli_fetch_array( $query ) ) {
'<option value=' . $list["id"]. '>' . $list["city_name"] . '</option>';
}
}
You should also learn to use parametrized queries instead of substituting variables, to prevent SQL injection. Until then, you should at least escape the parameters.

How to get data from database and create a dynamic select?

Im trying to create a select which is dynamic, for example if there is 3 item in the database gift, then it will create 3 select with value from the database lecturer. This is the javascript to create the select when the user click the button add.
Now after the user have create 3 select and submit it, if the user wish to edit back the data, how can I do it ?
function addField(area,field,limit)
{
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("select");
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
if(document.createElement)
{
var li = document.createElement("li");
var input = document.createElement("select");
var opt = document.createElement("option")
input.id = field;
input.name = field;
opt.value = "NULL";
opt.textContent = "NO LECTURER";
li.id = "li"+last_item;
input.appendChild(opt);
li.appendChild(input)
$(document).ready(function()
{
$.ajax
({
type:"post",
url: "event/data.php",
success: function(data)
{
console.log(data);
$(input).append(data);
}
});
});
field_area.appendChild(li);
}
}
Here example of what I have create,
http://i.imgur.com/je1MchL.png
Here how it works
http://i.imgur.com/c4ICTWt.png
So basically in the database have 5 data, so what im trying to do is in the next page it will automatic create the exact 5 select. How can I do this?
Thanks
Create a function (useful for reuse)
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
and call it:
// $options : return array from DB
$curr = 'some_key';
$select_name = 'my_select';
echo create_select($select_name,$options,$curr);
A complete working example:
<?php
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('effone_db');
$query = mysql_query("SELECT * FROM settings");
while ($row = mysql_fetch_array($query)) {
$options[$row['option']] = $row['option_value'];
}
echo create_select('settings',$options,'100');
?>
Let's assume that $options holds the resulting query.
So what you must do is loop thru the items and echo them inside a <select> tag.
like:
<html>
<body>
<select name='nameUrSelectHere'>
<?php
foreach($options as $option){
echo "<option value='" . $option['column_one'] . "'>" . $option['column_two'] . "</option>" ;
}
?>
</select>
</body>
</html>

Dynamic drop down menus

I want to create a dynamic drop down where the options of the second drop down changes after the selection of the first drop down.
The test.php file
<?php
$con=mysqli_connect("localhost","******","****","******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM countries");
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";
}
?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax
<script type="text/javascript">
function get_states() { // Call to ajax function
var country = $('#country').val();
var dataString = "country="+country;
$.ajax({
type: "POST",
url: "getstates.php", // Name of the php files
data: dataString,
success: function(html)
{
$("#get_state").html(html);
}
});
}
</script>
<?php
mysqli_close($con);
?>
and the gestates.php is:
<?php if ($_POST) {
$country = $_POST['country'];
if ($country != '') {
$sql1 = "SELECT * FROM states WHERE country_id=" . $country;
$result1 = mysql_query($sql1);
echo "<select name='state'>";
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result1)) {
echo "<option value='" . $row['id'] . "'>" . $row['state_name'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
However the above code does not work!
on change on first drop-down you need to make an ajax call which will get the options and you can then populate the next drop-down
Try adding single quotes around $country
$sql1 = "SELECT * FROM states WHERE country_id='" . $country . "'";
or
$sql1 = "SELECT * FROM states WHERE country_id='$country'";
EDIT: Also, you can only echo one result. Your second echo will be ignored by Jquery as the first will be considered a success.
You should format your results differently.
Perhaps a json encoded array.
In your php:
while($row = mysql_fetch_array($result1))
{
$data[$row['id']] = $row['state_name'];
}
echo json_encode($data);
In your Jquery set dataType: 'json'
$.each(html,function(key,value){
$("#get_state").append($('<option>',{
value:key,
text: value
}));
});

Categories