Mysql select box with jquery post - php

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.

Related

Selected rows not displaying when i display rows in Decrement order

Background :
when a user selects one of the option [ example : Undelivered ] in the drop down menu, then i am displaying only the rows which have that value [ example : Undelivered ]
<tr><th>
<select id="my_select" onchange="send_option();">
<option value="all">Status</option>
<?php
$query = "SELECT DISTINCT in_transit FROM do_order";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['in_transit'] . "'>" . $row['in_transit'] . "</option>";
?>
</select>
</th></tr>
<?php
$theBigQuery = "SELECT * FROM do_order WHERE 1";
if (isset($_POST['my_option']) && $_POST['my_option'] != "")
{
if($_POST['my_option'] == "all")
{
}
else
{
$theBigQuery .= " AND in_transit like '" . $_POST["my_option"] . "'";
}
echo "<script type='text/javascript'>function changeOption(){document.getElementById('my_select').value='".$_POST['my_option']."';} changeOption();</script>";
}
$orderrecords = $db_handle->runSelectQuery($theBigQuery);
?>
<tr><td id="<?php echo $orderrecords[$k]["tracking_id"];?>">
<?php echo $orderrecords[$k]["in_transit"]; ?>
</td></tr>
<form method="post" action"dashboard.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
script
function send_option ()
{
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
Requirement :
Now I want to display rows in decrement order , so in above code i changed below line . now rows are displaying in decrement order.
$theBigQuery = "SELECT * FROM do_order ORDER BY id DESC";
Issue :
but if i select any option in dropdown [ example : undelivered ] , its not displaying any rows.
Using you edit, when you select an option, your query will become :
$theBigQuery = "SELECT * FROM do_order ORDER BY id DESC AND in_transit like 'Undelivered'";
This is a wrong sql query!!
So to fix this; leave the $theBigQuery as it was, and after the if (isset( .. test, before running the query, add the ORDER BY clause :
$theBigQuery = "SELECT * FROM do_order WHERE 1";
if (isset($_POST['my_option']) && $_POST['my_option'] != "")
{
if($_POST['my_option'] == "all")
{
}
else
{
$theBigQuery .= " AND in_transit like '" . $_POST["my_option"] . "'";
}
echo "<script type='text/javascript'>function changeOption(){document.getElementById('my_select').value='".$_POST['my_option']."';} changeOption();</script>";
}
$theBigQuery .= " ORDER BY id DESC";
$orderrecords = $db_handle->runSelectQuery($theBigQuery);

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

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

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>';
}
}
}

How to bind select dropdownlist by selected value and other values from mysql in php

I have a project in php. When I bind select dropdown list with selected value as well as all others values inside the database the one value which is as selected will bind two times, one as first selected value and other as list values.
Below is my code.
$query1 = mysql_query("select * from pincode_master where pcode_id='1'");
while ($row1 = mysql_fetch_array($query1))
{
$city_id = $row1['city_id'];
$sql1="SELECT city_name from city_master where city_id='$city_id'";
$result1=mysql_query($sql1);
$row = mysql_fetch_row($result1);
#$city_name = $row[0];
$query11 = "select * from city_master";
$result11 = mysql_query($query11);
echo "<select name = 'cityname'>";
while (($row11 = mysql_fetch_row($result11)) != null)
{
echo "<option value = '{$row11['city_name']}'";
if ($city_name == $city_name)
echo "selected = 'selected'";
echo ">{$row11['city_name']}</option>";
}
echo "</select>";
}
You should write your query outside loop.
Write your code as below:-
// Check query error
$query1 = mysql_query( "select * from pincode_master where pcode_id='1'" ) or die( mysql_error());
// Check query error
$result11 = mysql_query( "select * from city_master" ) or die( mysql_error());
while ( $row1 = mysql_fetch_assoc( $query1 ) ) {
$city_id = $row1['city_id'];
echo "<select name = 'cityname'>";
while ($row11 = mysql_fetch_assoc( $result11 )) {
$selected = $row11['city_id'] == $city_id ? "selected = 'selected'" : '';
echo "<option value = '{$row11['city_name']}' $selected >". $row11['city_name'] ."</option>";
}
echo "</select>";
}
Hope it will help you :)
Please check this -
is that what you want ?
<select name="yourselection">
<option value="">--Select--</option>
<?php
$msql = mysql_query("SELECT * FROM tablename");
while($m_row = mysql_fetch_array($msql))
echo("<option value = '" . $m_row['table_column1'] . "'>" . $m_row['table_column2'] . "</option>");
?>
</select>
you will get more info here

Jquery input form will not pass variable when form submitted

I'm having trouble getting my variable to post in my form. I use jquery to load a box if the user wants to enter a new sub category.
Here is the select in the form
<select id="sub_cat1" name="sub_cat1">
<option value=""></option>
<option value="new">New Sub Cat</option>
<?php
$query = "SELECT sub_category FROM blog_posts GROUP BY sub_category";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) > 0) {
while ($row = mysqli_fetch_array($data)) {
$sub_category = $row['sub_category'];
echo '<option value="' . $sub_category . '">' . $sub_category . '</option>';
}
}
?>
</select>
<div id="load_sub_cat_box"></div>
This is the jquery
$(document).ready(function(){
$("#sub_cat1").on("keyup change", function() {
var prod = $("#sub_cat1").val();
if(prod == 'new'){
$("#load_sub_cat_box").append('<div style="padding-top:15px;">Enter New Sub Category</div><input type="text" name="sub_cat2" />');
}
});
});
And here is the form validate code
if($_POST['sub_cat1'] == "new"){
$sub_cat = mysqli_real_escape_string($dbc, trim($_POST['sub_cat2']));
}
else{
$sub_cat = mysqli_real_escape_string($dbc, trim($_POST['sub_cat1']));
}
If I select new, the box does load on the page but for some reason when form is submitted it will not load a variable for $sub_cat1. Is there something I don't know about jquery and forms?
You have two select elements with id="sub_cat1".
ids must be unique per page.
It is also invalid HTML, with a select inside a select.

Categories