Ajax multiple onchange dynamic dependent select box - php

would really appreciate your help on below issue. I have 3 dynamic dependent dropdowns. Scheme 1 is working when: Click Dropdown (Dd) 1=>Values change in Dd2=>Values change in Dd3. But I need Dd3 to be also dependent on Dd1 & Dd2.
I have ajax code and suppose it has mistakes:
$(document).ready(function(){
$('#country', '#state').on('change',function(){
var countryID = $('#country').val();
var stateID = $('#state').val();
if(countryID, stateID){
$.ajax({
type:'POST',
url:'search_city.php',
data: "country_id="+countryID+"&state_id="+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
})
});
ADDING PHP FILE:
<?php
include('connect.php');
if (isset($_POST["country_id"] || isset($_POST["state_id"]))) {
$query = $conn->query("SELECT * FROM city WHERE country_id =
".$_POST['country_id']." AND state_id = ".$_POST['state_id']." ORDER BY
city_name");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option
value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>

Related

How to load database data in chosen js dropdown

This is my html data:
<select class='ssc' id="selectCity" name='bachelorInstituteType' style='width: 200px;'>
<option value=""></option>
</select>
Chosen js and ajax to load data from database ---
$(document).ready(function() {
$(".ssc").chosen();
function loadlocation() {
$.ajax({
url: "loadlocation.php",
type: "POST",
success: function(data) {
$("#selectCity").append(data);
}
});
};
loadlocation();
});
loadlocation.php page data :
<?php
include "./includes/connection.php";
$sql = "SELECT * FROM city";
$result = mysqli_query($conn, $sql);
$data= "";
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data.= "<option value='{$row['cityName']}'> {$row['cityName']} </option>";
}
}
echo $data;
?>
here (cityName) data is coming form database. The problem is chosen select box is not showing the data but if I make a simple dropdown then it works. Please give me a solution.

mysql dropdown list when selected

I have a table with this structure and trying to use a dropdown to select a language from the list and then display the contents of respective language_id .. I am using mysql and php 5.4
My code is as follows, got stuck with looping and not sure how to get it
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages ");
if(mysql_num_rows($sql))
{
$select= '<select lang_desc="select">';
while($rows=mysql_fetch_array($sql))
{
$select.='<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>';
}
}
$select.='</select>';
echo $select ;
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '$select'");
while ($row = mysql_fetch_array($result))
{
}
Please help
I think this want minimum 2 PHP pages 1st for show data and 2nd for creat data in hear I didn't create DB connection please add it
in 1st I use jquery for getting data from 2nd PHP
show.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select id="lang" onchange="setlang(this.value)">
<?PHP
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages");
while($rows=mysql_fetch_array($sqL,MYSQL_ASSOC)){
echo '<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>'
}
?>
</select>
<div id='dis'></div>
<script type="text/javascript">
$( document ).ready(function() {
setlang($('#lang').val());
});
function setlang(val) {
$.ajax({
url: "data.php",
type: "POST",
data:{val:val},
success: function(result){
$("#dis").html(result);
}
});
}
</script>
data.php
<?php
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '".$_POST['val']."'");
$data="";
while ($row = mysql_fetch_array($result))
$data.="your row data for dis";
//
}
echo $data;
?>

Populating 3 dropdown using ajax, one after the other

I currently have this code that populates one dropdown using the value from previous dropdown, my problem now is how will I populate the 3rd dropdown using the result from the 2nd dropdown that was provided by the first dropdown?
This the current code.
accounttype will be the first dropdown.
accountcode will be the second dropdown based on the result of accounttype.
accounttitle should be the third dropdown based on the result of accountcode .
<div class="">
<label>accounttype :</label>
<select name="accounttype" id="accounttype">
<option value=''>------- Select --------</option>
<?php
$sql = "SELECT DISTINCT accounttype from earningsamendmentaccount";
include 'query/sqlsrv_query-global.php';
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
echo "<option value='".$row['accounttype']."'>".$row['accounttype']."</option>";
}
}
?>
</select>
<label>accountcode :</label>
<select name="accountcode" id="accountcode"><option>------- Select --------</option></select>
<label>accounttitle :</label>
<select name="accounttitle" id="accounttitle"><option>------- Select --------</option></select>
</div>
This is currently my ajax. This is within the same pag as my <div>
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select.php",
data:{accountcode:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accountcode").html(resp);
}
});
} else {
$("#accountcode").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
This is my earnings_amendment-employee_select.php .
<?php
include 'includes/session.php';
if(isset($_POST['accountcode'])) {
$accountcode=$_POST['accountcode'];
$sql = "select accountcode, accounttitle from earningsamendmentaccount where accounttype='$accountcode'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if(sqlsrv_num_rows($query) > 0) {
echo "<option value=''>------- Select --------</option>";
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
echo "<option value='".$row['accountcode']."'>".$row['accountcode']."</option>";
}
}
} else {
header('location: ./');
}
?>
What would be the best approach to do this to populate my third dropdown column? I tried creating a separate ajax for accounttitle but it didn't work.
have you tried
$('#your_second_dropdown').on('change', ()=> {
// your code here...
})

Ajax Modal : Return selected value to dropdown list into update form

I have been searching everywhere on this website and tried many solutions but none worked for me ! My problem is the following :
I have 2 tables :
TABLE INFO_STATUS (status_id, status_desc)
and
TABLE INFO_MARQUES (comp_id, comp_desc, comp_status(INT))
I am linking comp_status and status_id so that the row in INFO_MARQUES will get the current status.
What I would like to do? (EDITED FROM HERE)
2. get the current status value of info_marques located in comp_status automatically selected in the dropdown list when I open the update form
Example I want to update this company :
comp_id : 15
comp_desc : WEISS
comp_status : 1
Assuming that in table info_status :
status_id = 1
status_desc = FOLLOW-UP
When I open the update form I want to see this :
Check this
My Modal : (WORKING)
<select class="form-control" name="select_status">
<option value=''>Selectionner</option>
<?php
try {
$user = new USER();
$output = array();
$stmt = $user->runQuery("SELECT * FROM info_status");
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row) {
echo '<option value='.$row["status_id"].'>'.$row["status_desc"].'</option>';
}
}
catch(PDOException $e) {
printf('Erreur MySQL %d : %s', $e->getCode(), $e->errorInfo[2]);
exit;
}
?>
</select>
My Ajax
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
$.ajax({
url:"partials/test/fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#comp_name').val(data.comp_name);
$('#comp_parent').val(data.comp_parent);
$.each($('.select_status option'),function(a,b){
if($(this).val()== data.comp_status){
$(this).attr('selected',true)
}
});
$('.modal-title').text("Modifier un fichier client");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
then my PHP page : (WORKING)
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT *
FROM info_marques AS m
LEFT JOIN info_status AS s
ON s.status_id = m.comp_status
WHERE m.id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["comp_name"] = $row["comp_name"];
$output["comp_parent"] = $row["comp_parent"];
$output["comp_status"] = $row["status_desc"];
}
echo json_encode($output);
}
What am I missing here?
Cheers
I am not sure that if you want to populate drop down or else select data based on your response, But if you want to select the data and you have options already in drop down, you can do this:
$.each($('#select_status option'),function(a,b){
if($(this).val() == data.comp_status){
$(this).attr('selected',true)
}
});
But if you want to populate, you will have to append it using .append(). Do let me know if issue is something different and I may give you a solution.
As you are saying you need all the status and then show the current status. what i would suggest is use .done() method of ajax. It will come handy, like:
$("#select_status").prop('disabled',true)
$('#select_id').append('<option>Please wait... Fetching status</option>');
var status_options;
$.ajax({
url:"your_page_for_all_status.php",
success: function(e){
//add <option> tags to a variable using loop
}
}).done(function(){
$.ajax({
//ajax call to get current data. Compare and select data here. write your $.each here
}).done(function(){
$("#select_status").prop('disabled',false);
});
});
You should be good to go now!!! I am sorry if I made it complex.
I have found a solution that worked but not sure it is very clean though.
For those interested to know:
HTML
<select class="form-control" name="select_status" id="status">
<option value=''>Selectionner</option>
<?php
try {
$user = new USER();
$output = array();
$stmt = $user->runQuery("SELECT * FROM info_status");
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row) {
echo '<option value='.$row["status_id"].'>'.$row["status_desc"].'</option>';
}
}
catch(PDOException $e) {
printf('Erreur MySQL %d : %s', $e->getCode(), $e->errorInfo[2]);
exit;
}
?>
</select>
We list down all options in my table into the dropdown list
AJAX
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"partials/test/fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#comp_name').val(data.comp_name);
$('#comp_parent').val(data.comp_parent);
$('#status').val(data.select_status);
fetching the right value from PHP page and sending to dropdown list so that this value is selected while opening the form (THE PROBLEM WAS HERE)
$('.modal-title').text("Modifier un fichier client");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
PHP
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT *
FROM info_marques AS m
LEFT JOIN info_status AS s
ON s.status_id = m.comp_status
WHERE m.id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["comp_name"] = $row["comp_name"];
$output["comp_parent"] = $row["comp_parent"];
$output["status"] = $row["status_id"];
we return the match value
}
echo json_encode($output);
}

interlinked dropdown list is not working

i am working with interlinked dropdown list i.e on selection of one dropdown list ajax call generated and populated another dropdown list and so on.
So my problem is with data coming from server side,on selection of each dropdown list i want to filter the available-results also,but the data that coming from server side get appended to show div i.e dropdown-list items and results-items.i only want to append results-items to show div.
client side code
var country_code = $(this).val();
console.log(country_code);
if(country_code){
$('#loadingmessage').show();
$.ajax({
type:'POST',
url:'dependent.php',
data:'country_code='+country_code,
success:function(html){
console.log(html);
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
$('#results').html(html);
$('#loadingmessage').hide();
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
server side code
if(isset($_POST["country_code"]) && !empty($_POST["country_code"])){
$id = 1;
$code = $_POST['country_code'];
$code = mysqli_real_escape_string($conn,$code);
$query = "SELECT * FROM plus2_state WHERE country_code = '$code' ORDER BY state ASC";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while($row = mysqli_fetch_array($result)){
echo '<option class="state_option" value="'.$row['state_id'].'">'.$row['state'].'</option>';
}
}else{
echo '<option class="state_option" value="">State not available</option>';
}
$query_1 = "SELECT * from content where country_code = '$code' ORDER BY emp_name ASC";
$result_1 = mysqli_query($conn,$query_1) or die(mysqli_error($conn));
$row_count = mysqli_num_rows($result_1);
$_SESSION['result'] = array();
if($row_count > 0 )
{
while($content_rows = mysqli_fetch_array($result_1))
{
unset($_SESSION['result']);
echo "<div class='result'><div class='col-md-3 photo-grid' style = 'float:left'>
<div class = 'well well-sm'><h4><small>".$content_rows['emp_name']."</small></h4></div></div></div>";
$_SESSION['result'][$id] = array('name' => $content_rows['emp_name']);
}
}
else
{
echo "<div class = 'result'>no results found</div>";
}
$_SESSION['country_code'] = $code ;
//print_r($_SESSION['result']);
}

Categories