jquery php code to bind state and city from mysql database table - php

I have a form where in one table row a dropdown state field is there and in another tr another dropdown is there for selecting city, I need that before submitting the form when user selects a state from dropdown list automatically the city dropdown should fetch and display only those city from the selected state.
I don't want to use AJAX but want to do it with jquery.
Backend database has two tables one is state with two fields id and state, second is city table having 3 fields id, state and city where state is my foreign key.
How can I do it with jquery any help regarding this will be appreciated since I am a newbie, please help

If you don't want to use ajax you can always preload the full list of states with cities into a javascript object and call it from there.
Example:
<select id="stateDrop">
<option value="state1">State 1</option>
<option value="state2">State 2</option>
</select>
<select id="cityDrop"></select>
<script>
var cities = {'state1':['city_one', 'city_two', 'city_three'], 'state2':['city_four', 'city_five', 'city_six']};
$('#stateDrop').on('change', function(){
var cityList = cities[$(this).val()];
console.log(cityList);
var output = '';
$(cityList).each(function(k, v){
output += '<option value="'+v+'">'+v+'</option>';
});
$('#cityDrop').html(output);
});
</script>
Fiddle

If you want to avoid using an ajax call, you will need to build a mapping from state-id's to lists of cities. Then bind a function to the change event of the state select-element, and populate the city select-element with the values.
Assuming State ID 0 has the cities A and B, with city id's 0 and 1:
var map = [[{id:0,name:"A"},{id:1,name:"B"}]]
$("#states").on("change",function() {
var cities = map[$(this).val()];
$("#cities option").remove(); //remove previous options
$.each(cities, function(i,e) {
$("#cities").append('<option value="'+e.id+'">'+e.name+'</option>');
});
});
Example: http://jsfiddle.net/HQLQU/
The php/mysql part for building the JS-map could be something like this (untested!):
$query = "SELECT city_id, city_name, state_id FROM cities";
$result = mysql_query($query); //or preferably use a more modern extension
$cities = array();
foreach (mysql_fetch_assoc($result) as $row) {
$cities[$row['state_id']][] = array("id"=>$row['city_id'],"name"=>$row['city_name']);
}
echo "var map = " . json_encode($cities);

Related

How can I best put a drop down list or select tag inside a html table - And then update a row if changed to mysql? complicated

I have a database containing a name and a status column. It contains data displayed in a table (obvious!). So, I want users to be able to select the status column's data and change it to any value listed in the drop down list. After the selection, they need to click a button that will update the selected row to the mySQL database.
How can I achieve this with PHP scripting and HTML?
Here is my code for displaying the data in a table on the website: (Pay no attention to phpReportGenerator.php- its only drawing the columns as per sql table)
<?php
include_once('includes/phpReportGenerator.php');
$prg = new phpReportGenerator();
$prg->width = "100%";
$prg->cellpad = "10";
$prg->cellspace = "0.5";
$prg->border = "1";
$prg->header_color = "#307D7E";
$prg->header_textcolor="#FFFFFF";
$prg->body_alignment = "left";
$prg->body_color = "#C6DEFF";
$prg->body_textcolor = "#000000";
$prg->surrounded = '1';
//$prg->font_name = "Boishakhi";
mysql_connect("localhost","username","password");
mysql_select_db("my_database");
$res = mysql_query("select * from table");
$prg->mysql_resource = $res;
//$prg->title = "Test Table";
$prg->generateReport();
?>
OR
Can somebody show me a easier/more effective way to do this?
Here is the sample code that you can use to update your mysql database by sending request to the server to access process_mysql.php :
<select onchange="update_mysql();">
<option value="1">option 1 </option>
<option value="2">option 2 </option>
</select>
Jquery function with ajax post request:
<script>
update_mysql(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"process_mysql.php",
data:"id="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
</script>

How To create a Dependable Dropdown From Two Tables

I have two tables "oc_t_item_car_make_attr" , "oc_t_item_car_model_attr"
So how can i make a Dependable Dropdown From these Two Tables?
You can only do this by Ajax.
Following is city country reference site, you can get idea from that.
Referance Site
if you stuck any where feel free to ask me.
Actually didn't understand question very well, but you probably want something like this:
SELECT * FROM oc_t_item_car_make_attr
INNER JOIN oc_t_item_car_model_attr
ON oc_t_item_car_model_attr.fk_i_make_id = oc_t_item_car_make_attr.pk_i_id
WHERE oc_t_item_car_make_attr.pk_i_id = ?
You need to insert id in the place of question mark.
Here is the entire code what your looking for:
Below code will display all car names from database dynamically:
<select name="cars" id="carmodels">
<option value="">select</option>
<?php
$qry = mysqli_query("select * from oc_t_item_car_make_attr");
while($row=mysqli_fetch_array($qry)){
echo "<option value=".$row['pk_i_id'].">".$row['s_name']."</option>";
}
?>
</select>
Below result will display car models dependent on the names selected above:
html:
<select name="models" id="models">
</select>
you need to use ajax to get the car models from database:
$(document).on('change','#carmodels',function(){
var value = $(this).val();
$.ajax({
url: "demo.php",
type: "GET",
data: { id : value},
success: function(data){
$("#models").html(data);
}
});
demo.php:
<?php
include "connection.php"; //database connection code
$qry = mysql_query("SELECT * FROM oc_t_item_car_make_attr
INNER JOIN oc_t_item_car_model_attr
ON oc_t_item_car_model_attr.pk_i_id = oc_t_item_car_make_attr.pk_i_id
WHERE oc_t_item_car_make_attr.pk_i_id =".$_GET['id'].");
while($row=mysqli_fetch_array($qry)){
echo "<option value=".$row['pk_i_id'].">".$row['s_name']."</option>";
}
?>
Hey you can do this by ajax
Reference Link 1
Reference Link 2
also study inner join

Cascading jQuery Dropdowns with JSON and Multiple MySQL Tables using PHP

I'm fairly new to PHP and MySQL, have a little experience with jQuery and almost no experience with JSON, just to give you some background. I am trying to implement cascading dropdowns in my form.
I have two tables:
|city|
|city_id INT| - PK
|city VARCHAR (45)|
|state_state_id INT | - FK
|state|
|state_id INT| - PK
|state VARCHAR (25)|
Here's my form:
State:<br />
<select name="state" id="stateName">
<?php foreach($rows as $row): ?>
<option value="<?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>"><?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>
</option>
<?php endforeach; ?>
</select>
<br /><br />
City:<br />
<select name="city" id="cityName"></select>
<input type="submit" name="work_order_submit" id="" value="Add Work Order" />
I populate the State dropdown with this query:
$query = "SELECT * FROM state WHERE 1 ORDER BY state";
try{
$stmt = $db->prepare($query);
$stmt->execute();
}catch(PDOException $ex){
//On production remove getMessage.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
Here's the jQuery I've created to run the JSON and populate the City dropdown with the cascaded values from the state dropdown when a state is selected:
<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName:$('#stateName').val()},
function(data){
var select = $('#cityName');
var options = select.prop('options');
$('option', select).remove();
$.each(data, function(index, array){
options[options.length] = new Option(array['city']);
});
});
}
$(document).ready(function(){
populateCityName();
$('#stateName').on('change', function(){
populateCityName();
});
});
</script>
And here's the code in the state-names.php file (I connect to the database before this code):
$rows = array();
if(isset($_GET['stateName'])){
$query = "SELECT city FROM city INNER JOIN state ON city.state_state_id = state.state_id WHERE state = :state ORDER BY city";
$query_params = array(":state" => $_GET['stateName']);
try{
$stmt = $pdo->prepare($query);
$stmt->execute($query_params);
}catch(PDOException $ex){
//On production remove .getMessage.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
Nothing happens when I select the state in the form. I don't even get an error. I've tested the SQL and it runs fine and retrieves the values that I want, but for some reason that I can't figure out, the values aren't being cascaded into the City dropdown.
Any help is very much appreciated.
EDIT: As I'm doing more debugging and realizing a few things, this is what I've found so far. The JSON comes in like this:
[{"city":"Salt Lake City"},{"city":"Toole"},{"city":"Provo"},{"city":"St. George"}]
I now know the JSON is working correctly. When I changed the dropdown selection in the state dropdown to a state that I know had entries for the cities, the city dropdown showed blank 'option' fields for the number of entries that there actually were. So, using the answer below and MANY different tutorials on cascading dropdowns and chained dropdowns, I finally figured it out. I've submitted an answer with the working code.
Can you try:
$.each(data, function(index, array){
// new Option(text [, value, defaultSelected, selected]);
select.add(new Option(array['city'], index), null);
});
??
All of the code above worked except the jQuery function. Well, the jQuery worked for what I told it to do, not for what I really wanted the code TO DO... Big difference.
Here's the working jQuery that populates the city dropdown based on a selection made in the state dropdown:
<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName: $('#stateName').val()},
function(data){
var html = '<option value="';
var htmlEnd = '</option>';
var options = '';
var select = $('#cityName');
$('option', select).remove();
$.each(data, function(index, array){
options += html + array['city'] + '">' + array['city'] + htmlEnd;
});
$('#cityName').append(options);
});
}
$(document).ready(function(){
populateCityName();
$('#stateName').on('change', function(){
populateCityName();
});
});
</script>
Before, the code would find the number of entries and the select box would show this number, but the selections were blank. With this code, the number of entries is found, but the values for those entries also show. Hope this helps someone else later.

adding value and name to select box

<?php
$sql = "SELECT `docid`, `fullname` FROM `doctors` ORDER BY fullname ASC";
$result = $database->query($sql) or die('cannot connect to the database');
while($row = mysql_fetch_array($result))
{
echo"<option value= ".$row['docid'].">".$row['fullname']."</option>";
}
?>
This is my select box which i am populating through datbase table.
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
i want to make this one as SELECTED ITEM ON THE Select box
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>')
});
This is my jquery code. When i click ".sheUpdate" link i have couple of values that i am grabing using attr function. i am grabing depatment name and department value which i want to show as the SELECTED ITEM ON THE SELECT BOX
I think we need to see more code to be able to properly help. What is the html code of the element with the .sheUpdate class?
Does this link element actually have attributes dptname and dptid?
What is the code you use on #Deptmentselectbox?
The code you added is working properly.
just need to set the new added element as selected.
please check this fiddle
Also please let me know what value you get if you write this
alert($(this).attr('dptname'));
alert($(this).attr('dptid'));
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>')
$("#Deptmentselectbox").get(0).selectedIndex = 0;
// OR $("#Deptmentselectbox").val(deptid);
});
Assuming that your initial select box is like this:
<select id="Deptmentselectbox">
<option value=''> Select a department </option>
</select>
To remove the placeholder on first option selected:
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
if($("#Deptmentselectbox").val() == '')
$("#Deptmentselectbox").html('<option value='+deptid+'>'+deptment+'</option>');
else
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>');
$("#Deptmentselectbox").val(deptid);
}
Here is a Solution Hope it Helps
$(document).ready(function(){
$("#test1").click(function(){
var data = $("#t").val();
var data1 = $("#r").val();
$("#try").prepend('<option value='+data+' selected="selected">'+data1+'</option>');
});
});
Click Here For Demo

Creating and populating a select dynamically

I have 2 tables, Provinces and Districts. I would like to populate a select field with options as District names based on which Province is chosen in another select. The Districts table has a ProvinceID field to reference which Province it belongs to. I know this is doable, I just can't figure it out. I also want to create and update the new Districts select without refreshing the page.
UPDATE: I'm writing it in PHP and MySQL, using jQuery as sparingly as possible.
In order to do it without AJAX, prepopulate a Javascript dataset... warning, if you have a lot of data this could be slow, but if it's a manageable list length, you could save some overhead from multiple AJAX requests loading the same data over and over.
var provinces = {};
provinces['province_a_id'] = [
{ name:'District A', id:'district_a_id' },
{ name:'District B', id:'district_b_id' }
];
provinces['province_b_id'] = [
{ name:'District C', id:'district_c_id' },
{ name:'District D', id:'district_d_id' }
];
function getDistricts( referenced_select ) {
var selected_province = $(referenced_select).val();
var district_select = $('#districts');
district_select.empty();
if ( provinces[selected_province] ) {
$.each( provinces[selected_province], function(i,v) {
district_select.append( $('<option value="' + v['id'] + '">').text( v['name'] ) );
} );
}
}
$(document).ready( function() {
$('#provinces').bind( 'change', function() {
getDistricts(this);
} );
} );
-- HTML
<select id="provinces" name="provinces">
<option value="province_a_id">Province A</option>
<option value="province_b_id">Province B</option>
</select>
<select id="districts" name="districts">
</select>
Make a php script and call it dp.php ( dp, short for data_provider, use any name you like). In dp.php
// get province id passed in via `post` or `get`
$pid = $_REQUEST['pid'];
// get the districts in that province
$query = "SELECT `district_id`, `district` FROM `districts` WHERE province_id` ='$pid'";
// link to your database
$link = mysqli_connect(HOST, USER, PASS, DBNAME);
// execute your query
$result = mysqli_query($link, $query);
// parse the options
while($row = mysqli_fetch_assoc($result)) {
$options .= '<option value="' . row['district_id'] . '">' . $row['district'] . "</option>\n";
}
// send options
echo $options
With the following markup in your page:
<select id="province" name="province">
<option value="ny">New York</option>
...
</select>
<select id="district" name="district">
</select>
Include the following jQuery:
// whenever a different province is selected
$('#province').change(function() {
// remove all options in district select
$('#district').html('');
// find the new province selected
var my_province = $('#province').val();
// get new options from server and put them in your district select
$('#district').get('path/to/dp.php?pid=' + my_province);
)};
You didn't state what server side technology you are using (if any). Here's an example in ASP.net - it should point you in the right direction:
http://www.mikesdotnetting.com/Article/97/Cascading-DropDownLists-with-jQuery-and-ASP.NET
I actually figured this out on my own using jQuery and post. On the primary select, I added onchange="getDistricts()" and used this for that function:
function getDistricts()
{
var province_id = $("#provinces").val();
$.post("handler.php",
{
"mode" : "get_districts",
"pid" : province_id
},
function(data)
{
$("#districts").html(data);
}, "text");
}
And then in handler.php, I have a case that catches the mode, and runs the following code:
<query on districts table>
while($row = $sql->fetchrow($result);
{
$id = $row['id'];
$name = $row['name'];
$html .= "<option value='$id' id='$id'>$name</option>";
}
echo $html;
I'm not a fan of this solution, and would really like something better, but it does what I need it to do for the moment. I hope this can help someone else out.

Categories