`I have a script that is returning the right values except for one little problem. Lid is returning 892 which is right, However; Cid which should return 16 its returning 89216 a combination of the two. How can I get Cid to just return 16?
$(document).ready(function()
{
$(".Doggie").change(function()
{
var LocationString ='Lid='+ $(this).val();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: LocationString,
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
});
$('.Kitty').live("change",function(){
var Lid = $('#Doggie').val(), // This is the value of the id="Doggie" selected option
Cid = $(this).val(); // This is the value of the id="Kitty" selected option
$.ajax({
type: "POST",
url: "ajax_area.php",
data: {"Lid":Lid,"Cid":Cid},
cache: false,
success: function (html) {
$(".Pig").html(html);
}
});
});
});
</script>
</head>
<body>
<div id="frame1">
<label>Place :</label>
<select name="Doggie" class="Doggie" id="Doggie">
<option selected="selected">--Select Place--</option>
<?php
$sql = mysql_query("SELECT tblLocations.RestID as Lid, tblRestaurants.RestName as name
FROM tblRestaurants INNER JOIN tblLocations ON tblRestaurants.RestID = tblLocations.RestID
GROUP BY tblLocations.RestID, tblRestaurants.RestName
ORDER BY tblRestaurants.RestName ASC");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].'">'.$row['name'].'</option>';
} ?>
</select>
<label>City :</label>
<select name="Kitty" class="Kitty" id="Kitty">
<option selected="selected">--Select City--</option>
</select>
<label>Area: :</label>
<select name="Pig" class="Pig" id="Pig">
<option selected="selected">--Select Area--</option>
</select>
</div>
</body>
</html>
ajax_city.php
<?php
require('config.php');
if($_POST['Lid'])
{
$Lid=$_POST['Lid'];
//$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblCities.CityName as name
FROM tblLocations INNER JOIN tblCities ON tblLocations.CityID = tblCities.CityID
WHERE tblLocations.RestID = $Lid
GROUP BY tblLocations.RestID, tblCities.CityName
ORDER BY tblCities.CityName ASC");
echo '<option selected="selected">--Select City--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
ajax_area.php
<?php
require('config.php');
if($_POST['Lid'])
{
//$Lid=$_POST['Lid'];
$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblAreas.AreaName as name
FROM tblLocations INNER JOIN tblAreas ON tblLocations.AreaID = tblAreas.AreaID
WHERE tblLocations.RestID = $Lid AND tblLocations.CityID = $Cid
GROUP BY tblLocations.RestID, tblAreas.AreaName
ORDER BY tblAreas.AreaName ASC");
echo '<option selected="selected">--Select Area--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
It was these two lines in the ajax-city.php file.
"SELECT tblLocations.CityId as Cid, tblCities.CityName as name
And
echo '<option value="'.$row['Cid'].'">'.$row['name'].'</option>';
Related
I want to Hide and Show the "City" label.
Show only if I choose specific "State" if not hide it again.
Country=USA> State=Texas> Show the City label.
Country=USA> State=New York> Hide the City label
$(document).ready(function() {
// Country dependent ajax
$("#country").on("change", function() {
var countryId = $(this).val();
$.ajax({
url: "action.php",
type: "POST",
cache: false,
data: {
countryId: countryId
},
success: function(data) {
$("#state").html(data);
$('#city').html('<option value="">Select city</option>');
}
});
});
// state dependent ajax
$("#state").on("change", function() {
var stateId = $(this).val();
$.ajax({
url: "action.php",
type: "POST",
cache: false,
data: {
stateId: stateId
},
success: function(data) {
$("#city").html(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<div class="col-md-4">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM countries";
$result = $con->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<br />
<!-- State dropdown -->
<label for="country">State</label>
<select class="form-control" id="state">
<option value="">Select State</option>
</select>
<br />
<!-- City dropdown -->
<label for="country">City</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
Action.php
<?php
// Include the database connection file
include('db_config.php');
if (isset($_POST['countryId']) && !empty($_POST['countryId'])) {
// Fetch state name base on country id
$query = "SELECT * FROM states WHERE country_id = ".$_POST['countryId'];
$result = $con->query($query);
if ($result->num_rows > 0) {
echo '<option value="">Select State</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['state_name'].'</option>';
}
} else {
echo '<option value="">State not available</option>';
}
} elseif(isset($_POST['stateId']) && !empty($_POST['stateId'])) {
// Fetch city name base on state id
$query = "SELECT * FROM cities WHERE state_id = ".$_POST['stateId'];
$result = $con->query($query);
if ($result->num_rows > 0) {
echo '<option value="">Select city</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['city_name'].'</option>';
}
} else {
echo '<option value="">City not available</option>';
}
}
?>
try to add a condition inside the success callback function of the state dependent ajax request
success: function(data) {
$("#city").html(data);
if ($("#state").val() === "Texas") {
$("#city").parent().prev("label[for='country']").show();
} else {
$("#city").parent().prev("label[for='country']").hide();
}
}
It would be easier if the label was wrapping the select or the label and select was inside a div but here you are
You could just test the state since I expect you do not have other countries with a state called Texas
This goes anywhere
$("form").on("change", "select", function() {
const country = $("#country").val();
const state = $("#state").val();
const show = country === "USA" && state === "Texas";
$("$city").toggle(show);
$("$city").prev().toggle(show); // label
})
I am working on a project where data about therapists is stored in a database, I have 5 dropdowns on my page and I want the data to be fetched based on the dropdown values selected by the user.
<div id="dropdowns">
<form method="post">
<?php
session_start();
$username = "root";
$password = "";
$database = "align";
$mysqli = new mysqli("localhost", $username, $password, $database);
$sql = "SELECT DISTINCT `Designation` FROM `therapists`";
if($res = $mysqli->query($sql))
{
echo '<div class="select">
<select id="profession" name="profession" onchange="getSelectDesignation(this.value);">
<option selected disabled>Filter by Profession</option> ';
while ($row = $res->fetch_assoc()) {
echo "<option value='" . $row['Designation'] ."'>" . $row['Designation'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$ids = "SELECT DISTINCT `Identifies As` FROM `therapists`";
if($res = $mysqli->query($ids))
{
echo '<div class="select">
<select id="idas" name="idas" onchange="getSelectIdentifiesas(this.value);">
<option selected disabled>Identifies as</option> ';
while ($row = $res->fetch_assoc()) {
echo "<option value='" . $row['Identifies As'] ."'>" . $row['Identifies As'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$clgr = "SELECT DISTINCT `Client Group` FROM `therapists`";
if($res = $mysqli->query($clgr))
{
echo '<div class="select">
<select id="clgr" name="clgr" onchange="getSelectClientGroup(this.value);">
<option selected disabled>Client Group</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Client Group'] ."'>" . $row['Client Group'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$istr = "SELECT DISTINCT `Issues Treated` FROM `therapists`";
if($res = $mysqli->query($istr))
{
echo '<div class="select">
<select id="istr" name="istr" onchange="getSelectIssuesTreated(this.value);">
<option selected disabled>Issues treated</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Issues Treated'] ."'>" . $row['Issues Treated'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$lan = "SELECT DISTINCT `Languages` FROM `therapists`";
if($res = $mysqli->query($lan))
{
echo '<div class="select">
<select id="idas" name="lan" onchange="getSelectLanguages(this.value);">
<option selected disabled>Languages</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Languages'] ."'>" . $row['Languages'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
?>
</form>
</div>
Whenever a user selects a dropdown option, a specific function for each dropdown gets called which takes the value of the option selected and sends it to a different page called fetch_data which displays the information about the therapists.
function getSelectDesignation(val1)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option1:val1,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectIdentifiesas(val2)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option2:val2,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectClientGroup(val3)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option3:val3,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectIssuesTreated(val4)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option4:val4,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectLanguages(val5)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option5:val5,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
Below is the code in my fetch_data page :
<?PHP
session_start();
$username = "root";
$password = "";
$database = "align";
$mysqli = new mysqli("localhost", $username, $password, $database);
$state1 = $_POST['get_option1'];
$state2 = $_POST['get_option2'];
$state3 = $_POST['get_option3'];
$state4 = $_POST['get_option4'];
$state5 = $_POST['get_option5'];
$loc = $_SESSION['location'];
$find="SELECT * FROM `therapists` AS `T` inner join `personal details` as `P` ON `T`.`Therapist ID` = `P`.`Therapist ID` WHERE(`Location` LIKE '%".$loc."%' AND `Designation` LIKE '%".$state1."%' AND `Identifies As` LIKE '%".$state2."%' AND `Client Group` LIKE '%".$state3."%' AND `Languages` LIKE '%".$state5."%' AND `Issues Treated` LIKE '%".$state4."%')";
if ($result = $mysqli->query($find)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["Therapist ID"];
$field2name = $row["Name"];
$field3name = $row["Designation"];
$field4name = $row["Identifies As"];
$field5name = $row["Client Group"];
$field6name = $row["Languages"];
$field7name = $row["Issues Treated"];
$field8name = $row["Location"];
$field9name = $row["Phone Number"];
$field10name = $row["Intro"];
$field11name = $row["Instagram Link"];
$field12name = $row["Linkedin Link"];
$field13name = $row["Aasha URL"];
echo '<div id="profile-card">
<div id="info">
<div class="name-desig-img">
<div class="name-desig">
<a class="therapist-name" href="http://localhost/aasha/profile.php/'. $field2name .'">';echo $field2name;echo'</a>
<p>';echo $field3name;echo'</p>
</div>
<div class="p-img">
<img class="prof-img" src="';echo $field14name;echo'">
</div>
</div>
<div class="intro">
<p>';echo $field10name;echo'</p>
</div>
<div class="location">
<p>';echo $field8name;echo'</p><p>
</div>
</div>
<div id="links">
<div id="t-socials">
<div class="tp"><a class="t-links" href="';echo $field13name;echo'">';echo' Profile </a></div>
<div class="tli">|</div>
<div class="tli"><a class="t-links" href="';echo $field12name;echo '"><i class="fab fa-linkedin">';echo'</i></a> </div>
<div class="tli">|</div>
<div class="tli"><a class="t-links" href="';echo $field11name;echo '"><i class="fab fa-instagram-square">';echo'</i></a></div>
</div>
<p class="showphone">
<span class="clickshow" style="display: inline;"><b>Show Phone Number</b></span>
<span class="hiddenphone" style="display: none;">
<span>';echo $field9name;echo'</span>
</span>
</p>
</div>
</div>';
}
/*freeresultset*/
$result->free();
}
?>
Now the issue is whenever I select a dropdown option the value for the other dropdowns is empty and I get the undefined array key error in PHP. For example, if I select option1 which is the first dropdown, I get undefined array key error for option2, option3, option4, and option5. If I select option2 I get undefined array key error for option1, option3, option4, and option, and so on. I need to find a way to make the query work even if no option is selected in 1 or more dropdowns.
You can check if the options are set by using
isset() and if the value is not set, Just assign '' a string of length zero to those variables.
if(isset($_POST['get_option1'])){
$state1 = $_POST['get_option1'];
}else{
$state1 = '';
}
Similarly for all other variables.
First of all, only 1 request can be made in ajax at once, according to your code, the request is sent when onchange() so only 1 request will be made.
Everything looks fine but you are fetching all variables from _POST where as only 1 is sent at a time, so, you need to send all the variables at a time for your query $find="SELECT * FROM `therapists` AS `T` inner join `personal details` as `P` ON `T`.`Therapist ID` = `P`.`Therapist ID` WHERE(`Location` LIKE '%".$loc."%' AND `Designation` LIKE '%".$state1."%' AND `Identifies As` LIKE '%".$state2."%' AND `Client Group` LIKE '%".$state3."%' AND `Languages` LIKE '%".$state5."%' AND `Issues Treated` LIKE '%".$state4."%')"; to work.
Do something like this.....
<div id="dropdowns">
<form>
<!-- Your selectors here -->
<select id="idas" name="lan">
<option> ...... </option>
</select>
<select id="clgr" name="lan">
<option> ...... </option>
</select>
<select id="istr" name="lan">
<option> ...... </option>
</select>
<input type="button" onclick = "gettheValues()" value="GetIt">
</form>
</div>
Java script
function gettheValues()
{
var val1 = document.getElementById("idas").value;
var val2 = document.getElementById("clgr").value;
var val3 = document.getElementById("istr").value;
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option1:val1,
get_option2:val2,
get_option3:val3
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});//Send values all together...
}
I guess nothing need to be changed in php code.
And I need to find a way to make the query work even if no option is selected in 1 or more dropdowns. what you meant by this?
If those states state1 - state5 are important for your query then it is not possible to run that query.
It is you who know the importance of the states in that query so it won't be appropriate to answer.
If you think you can query as per different selectors do like this.
<?php
if(isset($_POST['get_option1']))
{
//appropriate query here
$query = "Your query with option1";
}
if(isset($_POST['get_option2']))
{
//appropriate query here
$query = "Your query with option2";
}
...
..etc to option5
//Here your result of query with html
?>
For any queries comment below, if you need a working example I will make one.
Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}
I am trying to get multiple value from multiple select textbox and use the same value in PHP for adding the SUM.
My code is:
function get_amount() {
var x = $('#work').val();;
alert(x);
$.ajax({
type: "POST",
url: "get-sum.php",
data: 'id=' + x,
success: function(data) {
alert(data);
//$('#html').load(document.URL + ' #html');
}
});
}
<select class="select2 select2-multiple" multiple="multiple" data-placeholder="Choose" name="work[]" id="work" onchange="get_amount()">
<option value="1" >option 1</option>
<option value="2"> OPtion 2 </option>
<option value="3"> OPtion 3</option>
</select>
And My php file as :
$id = $_POST['id'];
function getAmount($id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT
(amount)
FROM work
WHERE id = ?
");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $amount;
}
$sql = getAmount($id);
echo $sql;
Error which i am getting is the data which i am getting from multiple select is like 5,6,7 and its always hitting the php file at id 5. And the second problem how i will be able to add all $sql data.
I have done some changes in my PHP code :
$id = $_POST['id'];
$sum = 0;
for($i = 0; $i<count($id); $i++) {
$sum = $sum + getAmount($id[$i]);
}
echo $sum;
function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->fetch();
return $amount['total'];
}
I have my index.php file which load all the countries correctly as seen in this image:
Also this is what I've seen in the first load:
<div class="content">
<?php
include("config.php");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country_id]>$myrow[country]</option>");
}
?>
</select>
<br>
<select name="state" id="state">
<option value="">Select State</option>
</select>
<br>
<select name="city" id="city">
<option value="">Select City</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
Then I have the ajaxData.php file as below:
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = "SELECT state FROM states WHERE country = ".$_POST['country_id'];
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
//Count total number of rows
$get_total_rows = pg_numrows($results);
//Display states list
if($get_total_rows > 0){
echo '<option value="">Select state</option>';
while($myrow = pg_fetch_assoc($result)) {
echo '<option value="'.$myrow['state_id'].'">'.$myrow['state'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
Once I select the country I see the following:
Since the text in the selectors has changed from "Select a State" to "Select country first", it seams that in my javascript funtion when $('#country').on('change',function() is getting into
else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
Instead of going through:
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
There is obviously something that is not working but I'm not able to see what it is.
Any help would be appreciated.