dropdown based on previous dropdown - php

I am trying to create a cascading dropwdown for state, city and zip. I have part of it working like when a user chooses a state the corresponding city list comes up, but when a user chooses a city no zips come up. Not sure what i am missing or doing wrong. Can someone please help me with this?
index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="container">
<div id="body">
<div id="dropdowns">
<div id="center" class="cascade">
<?php
$sql = "SELECT DISTINCT state FROM tbl_zip ORDER BY state ASC";
$query = mysqli_query($con, $sql);
?>
<label>State:
<select name="state" id = "state">
<option value="">Please Select</option>
<?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC )) { ?>
<option value="<?php echo $rs["state"]; ?>"><?php echo $rs["state"]; ?></option>
<?php } ?>
</select>
</label>
</div>
<div class="cascade" id="city"></div>
<div id="zip" class="cascade"></div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select#state").change(function(){
var state = $("select#state option:selected").attr('value');
//alert(state);
$("#city").html( "" );
$("#zip").html( "" );
if (state.length > 0 ) {
//alert(state.length);
$.ajax({
type: "POST",
url: "fetch_state.php",
data: "state="+state,
cache: false,
beforeSend: function () {
$('#city').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#city").html( html );
}
});
}
});
$("select#city").change(function(){
var city = $("select#city option:selected").attr('value');
// alert(state_id);
if (city.length > 0 ) {
$.ajax({
type: "POST",
url: "fetch_city.php",
data: "city="+city,
cache: false,
beforeSend: function () {
$('#zip').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#zip").html( html );
}
});
} else {
$("#zip").html( "" );
}
});
});
</script>
</body>
</html>
fetch_state.php
<?php
include("connection.php");
//var_dump($_POST);
$state = trim(mysqli_escape_string($con, $_POST["state"]));
$sql = "SELECT DISTINCT city FROM tbl_zip WHERE state = '".$state ."' ORDER BY city";
$count = mysqli_num_rows( mysqli_query($con, $sql) );
if ($count > 0 ) {
$query = mysqli_query($con, $sql);
?>
<label>City:
<select name="city" id="city">
<option value="">Please Select</option>
<?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $rs["city"]; ?>"><?php echo $rs["city"]; ?></option>
<?php } ?>
</select>
</label>
<?php
}
?>
fetch_city.php
<?php
include("connection.php");
$city = trim(mysqli_escape_string($con, $_POST["city"]));
$sql = "SELECT DISTINCT zip FROM tbl_zip WHERE city = '".$city ."' ORDER BY zip ASC";
$count = mysqli_num_rows( mysqli_query($con, $sql) );
if ($count > 0 ) {
$query = mysqli_query($con, $sql);
?>
<label>zip:
<select name="zip" id="zip">
<option value="">Please Select</option>
<?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $rs["zip"]; ?>"><?php echo $rs["zip"]; ?></option>
<?php } ?>
</select>
</label>
<?php
}
?>

Here is the link, I think this will help :
http://www.91weblessons.com/php-ajax-country-state-city-drop-down/
happyCoding :D

Move the javascript code
$("select#city").change(function(){
var city = $("select#city option:selected").attr('value');
// alert(state_id);
if (city.length > 0 ) {
$.ajax({
type: "POST",
url: "fetch_city.php",
data: "city="+city,
cache: false,
beforeSend: function () {
$('#zip').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#zip").html( html );
}
});
} else {
$("#zip").html( "" );
}
});
in fetch_state.php file along the generation of select.

Related

AJAX POST Not Returning php mysql ajax

I'm trying to get data from the database using ajax to insert it in other element but the post data not passing to get-data.php
so what the reason can be and the solution
addBuilding.php
<?php
require_once("./dbConfig.php");
$selectIL = "SELECT * FROM iller ";
$selectIL = $db->prepare($selectIL);
$selectIL->execute();
$res = $selectIL->get_result();
?>
<form action="" method="post">
<select name="pp" id="cites">
<option value="">-select state-</option>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['il_adi'] ?></option>
<?php
}
?>
</select>
<select name="district" id="district">
<option value="">-select district-</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="getdata.js"></script>
getdata.js
$(document).ready(function() {
$("#cites").change(function() {
if ( $("#cites").val()!="") {
$("#district").prop("disabled",false);
}else {
$("#district").prop("disabled",true);
}
var city = $("#cites").val();
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
success: function(result) {
$("#district").append(result);
}
});
});
});
get-data.php
I can see the form data in network inspection put no data passing to get-data.php
<?php
require_once("./dbConfig.php");
if (isset($_POST['pp'])) {
$cites = $_POST['cites'];
$selectIlce = "SELECT * FROM ilceler where il_id=? ";
$selectIlce = $db->prepare($selectIlce);
$selectIlce->bind_param("i", $cites);
$selectIlce->execute();
$res = $selectIlce->get_result();
?>
<?php
while ($row = $res->fetch_assoc()) {
?>
<option value="<?= $row['id'] ?>"><?= $row['ilce_adi'] ?></option>
<?php
}
}
?>
You need to echo the results in get-data.php
<?php
while ($row = $res->fetch_assoc()) {
?>
echo "<option value='". $row["id"]."'>".$row['ilce_adi']."</option>";
<?php
}
}
?>
1- Get data by serialize from form:
$("form").serialize()
2- Add dataType: "json" to ajax option:
$.ajax({
type: "POST",
url:"get-data.php",
data:$(city).serialize(),
dataType: "json",
success: function(result) {
$("#district").append(result);
}
});

how to change AJAX call from another php file to the same page

I created 2 dropdown lists where the second one is populated from database based on the option selected in the first one using Ajax.
It's working fine but I want to change the call in my ajax from url:"get-City.php" to the same page instead of creating get-city.php I want to put all the code in one page.
Here is my index.php
<?php
include('connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="">
<label>Country :</label>
<select name="country" id="country">
<option value=''>------- Select --------</option>
<?php
$query = 'SELECT DISTINCT Country FROM ****';
foreach ($dbDB->query($query) as $row) {
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<label>City :</label>
<select name="city" id="city"><option>------- Select --------</option></select>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#country").change(function() {
var country_name = $(this).val();
if(country_name != "") {
$.ajax({
url:"get-City.php",
data:{selected_country:country_name},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#city").html(resp);
}
});
} else {
$("#city").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
and City.php
<?php
include('connection.php');
if(isset($_POST['selected_country'])) {
$sql = "SELECT DISTINCT City FROM **** WHERE Country = '".$_POST['selected_country']."'ORDER BY City";
$res = $dbDB->prepare($sql);
$res->execute();
$count = count($res->fetchAll());
if($count > 0) {
echo "<option value=''>------- Select --------</option>";
foreach ($dbDB->query($sql) as $row) {
echo '<option value="'.$row["City"].'">'.$row["City"].'</option>'; }
} }
else { header('location: ./'); }
?>
Now I wanted to merge both files on the same page and make the AJAX call on the same page. Here is my updated file
<?php
include('connection.php');
if(isset($_POST['selected_country'])) {
$sql = "SELECT DISTINCT City FROM **** WHERE Country = '".$_POST['selected_country']."'ORDER BY City";
$res = $dbDB->prepare($sql);
$res->execute();
$count = count($res->fetchAll());
if($count > 0) {
echo "<option value=''>------- Select --------</option>";
foreach ($dbDB->query($sql) as $row) {
echo '<option value="'.$row["City"].'">'.$row["City"].'</option>'; }
} }
else { header('location: ./'); }
?>
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="">
<label>Country :</label>
<select name="country" id="country">
<option value=''>------- Select --------</option>
<?php
include('connection.php');
$query = 'SELECT DISTINCT Country FROM **** ORDER BY Country ASC';
foreach ($dbDB->query($query) as $row) {
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<label>City :</label>
<select name="city" id="city"><option>------- Select --------</option></select>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#country").change(function() {
var country_name = $(this).val();
if(country_name != "") {
$.ajax({
data:{selected_country:country_name},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#city").html(resp);
}
});
} else {
$("#city").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Everytime I select a country then second dropdown list is empty. Can you please advise me what I am missing ? Thank you.

Why do my dropdowns show the message "array(1) ..." for each dependent drop down?

I am designing a page that gathers study abroad information from students at my university. Each time you select a country, the drop down will then say array(1) { ["country"]=> string(6) "France" } (or a similar country) before it says "State:". Why is this?
Below is my code minus the UUID and the database connection.
<!DOCTYPE html>
<head>
<link href="Page2.css" rel="stylesheet">
<style>
.error {
color: #FF0000;
}
</style>
<link href="styles.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function go() {
var Count = document.getElementById("sa_yesno").options[document.getElementById("sa_yesno").selectedIndex].value;
if(Count==1) {
document.getElementById("info").style.display = 'none';
}
if(Count==2) {
document.getElementById("info").style.display = '';
}
}
$(document).ready(function(){
$("select#countryName").change(function() {
var country = $("select#countryName option:selected").attr('value');
//alert(country);
$("#state").html("");
$("#city").html("");
if (country.length > 0 ) {
//alert(country.length);
$.ajax({
type: "POST",
url: "fetch_state.php",
data: "country="+country,
cache: false,
success: function(html) {
$("#state").html( html );
}
//not sure about these last two parts
});//end ajax
}//end if
});//end countryName.change
});
</script>
<header>
<h1> University </h1>
<h2> Department </h2>
</header>
</head>
<?php
require 'dbc.php';
require 'uuid.php';
$countriesSQL = "SELECT DISTINCT Country FROM LOCATIONLOOKUP";
$countriesQuery = mysqli_query($conn, $countriesSQL);
while($countries[] = $countriesQuery->fetch_object());
array_pop($countries);
?>
<body>
<table><tr><td>
<div class="StyleDiv" >
<form action="Page3.php" method="post">
<p> Please share any of the information below that you are comfortable sharing about your study abroad experience, if applicable.</p>
<p> 1. Did you study abroad? </p>
<p><select onchange="go()" name="sa_yesno" id="sa_yesno">
<option value="1">No</option>
<option value="2">Yes</option>
</select></p>
<div class="styleDiv" id="info" style="display:none">
<p> 2. When did you study abroad? </p>
<p><select name="sa_term" id="sa_term">
<option value="Fall">Fall Semester</object>
<option value="Spring">Spring Semester</object>
<option value="J-term">J-Term</object>
<option value="Summer">Summer Term</object>
</select></p>
<p> Where did you study abroad?</p>
Country: <select name="countryName" id="countryName">
<option value="">Please Select</option>
<?php foreach($countries as $option) : ?>
<option value="<?php echo $option->Country; ?>"><?php echo $option->Country; ?></option>
<?php endforeach; ?>
</select></br>
<div id="state" class="cascade"></div>
<div id="city" class="cascade"></div>
<br/><br/>
<input type="submit" value="Continue" name="submit" id="submit" ONCLICK="window.location.href='Page3.php?'">
</div>
</form>
<?php
require 'dbc.php';
require 'uuid.php';
$studentID = $_SESSION["studentID"];
$studyid=null;
//can these be assigned values in the select tag above?
$countrySelected= $_POST["countryName"];
$stateSelected= $_POST["drop2"];
$citySelected= $_POST["drop3"];
//Select the locationID from the country, state, city that were specified
$sql2 = "SELECT LocID FROM LOCATIONLOOKUP WHERE Country = '" . $countrySelected . "'
AND StateProvince = '" . $stateSelected . "' AND City = '" . $citySelected . "';";
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query 2: ' . $query;
die($message);
echo "there was an issue";
}
while ($row = mysqli_fetch_assoc($result2)) {
$locationID = $row['LocID'];
}
$stmt = $conn->prepare(" INSERT INTO STUDYABROAD (Term, StudentID, LocID) VALUES ( ?, ?, ?, ?)");
$stmt->bind_param("ssss", $term, $studentID, $locationID);
$stmt->execute();
mysqli_close($conn);
?>
</body>
</html>
EDIT: Here is fetch_state.php
<?php
require 'dbc.php';
var_dump($_POST);
$country = trim(mysqli_escape_string($conn, $_POST["country"]));
$sql = "SELECT DISTINCT StateProvince FROM LOCATIONLOOKUP WHERE Country = '". $country ."' ORDER BY StateProvince";
$count = mysqli_num_rows( mysqli_query($conn, $sql) );
if ($count > 0) {
$query = mysqli_query($conn, $sql);
while($states[] = $query->fetch_object());
array_pop($states);
?>
<label>State:
<select name="state" id="drop2">
<option value="">Please Select</option>
<?php foreach($states as $option) : ?>
<option value="<?php echo $option->StateProvince; ?>"><?php echo $option->StateProvince; ?></option>
<?php endforeach; ?>
</select>
</label>
<?php
}
?>
<script src="jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function(){
$("select#drop2").change(function(){
var state = $("select#drop2 option:selected").attr('value');
// alert(state_id);
if (state.length > 0 ) {
$.ajax({
type: "POST",
url: "fetch_city.php",
data: "state="+state,
cache: false,
success: function(html) {
$("#city").html( html );
}
});
} else {
$("#city").html( "" );
}
});
});
</script>

Display Table based on dropdownlist selection in PHP

My table is not displayed when i select any project name. I guess the onchange function is not working properly but i couldn't figure out the problem.
Code is as follows:
<div class="span6">
<?php $sql = "SELECT * from login_projects WHERE login_id='".$record['login_id']."'";
$res_sql = mysql_query($sql); ?>
<label>Project Name <span class="f_req">*</span></label>
<!--<input type="text" name="city" class="span8" />-->
<select name="project_name" onchange="get_list_onnet()" id="project_name" class="span8">
<option value="">--</option>
<?php while($rec_sql = mysql_fetch_array($res_sql)){ ?>
<option value="<?php echo $rec_sql['project_id']; ?>">
<?php echo $rec_sql['project_name']; ?></option>
<?php } ?>
</select>
</div>
Function:
<script>
function get_list_onnet(){
var project_name=$("#project_name").val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: {action: 'get_list_onnet',list_onnet:project_name},
success: function()
{
document.getElementById("dt_a").style="block";
$("#dt_a").html(html);
}
});
};
</script>
<script>
$(document).ready(function() {
//* show all elements & remove preloader
setTimeout('$("html").removeClass("js")',1000);
});
</script>
Ajax.Php Page:
function get_list_onnet(){
$list_onnet=$_POST['list_onnet'];
$sql_list_onnet=mysql_query("SELECT * from projects,project_wise_on_net_codes
where projects.project_id = project_wise_on_net_codes.project_id AND
project_wise_on_net_codes.project_id='$list_onnet'");
$row1 = mysql_num_rows($sql_list_onnet);
if($row1>0)
{
echo "<tr><th>id</th><th>Project Name</th><th>Country Code</th><th>On-net prefix</th>
<th>Action</th></tr>";
$k = 1; while($row_list_onnet=mysql_fetch_array($sql_list_onnet))
{
$project3 = $row_list_onnet['project_name'];
$countrycode1 = $row_list_onnet['country_code'];
$prefix1 = $row_list_onnet['on_net_prefix'];
$id_proj = $row_list_onnet['project_id'];
$on_prefix = $row_list_onnet['on_net_prefix'];
echo "<tr><td>".$k."</td><td>".$project3."</td><td>".$countrycode1."</td>
<td>".$prefix1."</td><td><a href='process/update_process_onnet.php?ID=".$id_proj."&Onnet=".$on_prefix."'>Delete</a></td>
</tr>";
$k++;
}
}
else
{
echo "<script>alert('No Record Found')</script>";
}
}
The problem is that it is always going in the else condition and nothing is displayed in the table.

Dependent dropdown list working in php and not working in codeigniter

In the below code when i worked in php the dropdown are working well when exam name is selected corresponding course_code came and when i selected corresponding subject_code came.But Now i created controller and call the view in codeigniter when i select exam_name it is not populating the values and when i click upload it shows the course_code values and not populating subject_coide and when i click upload it populates subject_code.So anyone pls help me.
Upload1_site (controller)
<?php
class Upload1_site extends ci_controller
{
function index()
{
$this->load->view('new_view');
}
function upload()
{
$this->load->view('new1_view');
}
}//end of class ?>
new_view (View 1)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".hai").change(function()
{
var id=$(this).val();
// Please find the course_code, course_code was not found
var dataString = 'course_code='+ id;
$.ajax
({
type: "POST",
url: "upload1_site/upload",
data: dataString,
cache: false,
success: function(html)
{
$(".hai2").html(html);
}
});
});
$(".hai2").change(function()
{
var id2=$("#hai2").val();
alert(id2);
var dataString = 'subject_code='+ id2;
$.ajax
({
type: "POST",
url: "upload1_site/upload",
data: dataString,
cache: false,
success: function(html)
{
$(".hai3").html(html);
}
});
});
});
</script>
</head>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
File to import:
<input size='30' type='file' name='filename'>
<br>
Select Exam name:
<select name="hai" class="hai" id="hai">
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("slseatapp") or die(mysql_error());
$query="select distinct exam_name from examcourse";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['exam_name']."'>".$nt['exam_name']."</option>";
}
?>
</select>
<br>
<span class="hai2">
Course code:
<select name="hai2" id="hai2">
<?php if($_REQUEST['hai']){?>
<option>Select</option>
<?php
$query="SELECT distinct course_code FROM examcourse where exam_name = '".$_REQUEST['hai']."' ";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['course_code']."'>".$nt['course_code']."</option>";
}
?>
<?php }else{?>
<option>Select</option>
<?php }?>
</select>
</span>
<br>
<span class="hai3">
Subject code:
<select name="hai3" id="hai3">
<?php if($_REQUEST['hai2']){?>
<option>Select</option>
<?php
$query="SELECT distinct subject_code FROM coursesubject where course_code = '".$_REQUEST['hai2']."'";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['subject_code']."'>".$nt['subject_code']."</option>";
}
?>
<?php }else{?>
<option>Select</option>
<?php }?>
</select>
</span>
<br>
<input type="submit" name="submit" value="Upload"></form>
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("slseatapp") or die(mysql_error());
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
//Import uploaded file to Database
$row = 1;
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$var = $_POST['hai'];
$var2 = $_POST['hai2'];
$var3 = $_POST['hai3'];
//$res=mysql_fetch_array(mysql_query("SELECT subject_code FROM coursesubject where course_code = '".$var1."'"));
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//Update Database Values
$import="insert into student_table (id,register_number,name,course_code,subject_code,exam_name) VALUES('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[1])."','".mysql_real_escape_string($data[2])."','$var2','".$var3."','$var')";
//$import="replace into student_table (id,register_number,name,course_code,subject_code,exam_name) VALUES('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[1])."','".mysql_real_escape_string($data[2])."','$var','$var1','$var2')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
echo"<script>alert('Uploaded Successfully');</script>";
}else{
echo"<script>alert('Failed');</script>";
}
}
?>
new2_view (view 2)
<script language="javascript">
function changeSelection(value){
var length = document.getElementById("hai3").options.length;
if(value == 0){
for(var i = 1;i<length;i++)
document.getElementById("hai3").options[i].selected = "selected";
document.getElementById("hai3").options[0].selected = "";
}
}
</script>
<?php
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("slseatapp") or die(mysql_error());
if($_POST['course_code']){
#$exam_name=$_POST['course_code'];
?>
Course code: <select name="hai2" id="hai2">
<option >Select</option>
<?php
$query="SELECT distinct course_code FROM examcourse where exam_name = '$exam_name' ";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['course_code']."'>".$nt['course_code']."</option>";
}
?>
</select>
<?php }
if($_POST['subject_code']){
#$subject_code=$_POST['subject_code'];
?>
Subject code:
<select name="hai3" multiple onChange="changeSelection(this.value)" id="hai3">
<option value="0">Select</option>
<?php
$query="SELECT subject_code FROM coursesubject where course_code = '".$subject_code."'";
$result = mysql_query($query);
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['subject_code']."'>".$nt['subject_code']."</option>";
}
?>
</select>
<?php }?>
try this one
put this one
var base_url="<?=base_url()?>"
somewhere inside the script tag may be before
$(document).ready(function(){
line
and change the line
url: "upload1_site/upload",
with
url: base_url+"upload1_site/upload",
please let me know if it works or not.

Categories