How to keep jQuery auto populated dropdown result selected? - javascript

I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?
Here is my HTML & PHP
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="job_category">Select Job Category</label>
<select name="job_category" id="category" class='form-control'>
<option value='' selected='selected' disabled='disabled'>Select Job Category</option>
<?php
$sql="select * from job_category ";
foreach ($db->query($sql) as $row) {
?>
<option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class='row form-group'>
<div class='col-md-12'>
<label class='sr-only' for='job_subcategory'>Select Job Industry</label>
<select name='job_subcategory' id='sub-category' class='form-control'>
<option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
</select>
</div>
</div>
Here is my JQ
$(document).ready(function() {
$('#category').change(function(){
var cat_id=$('#category').val();
$('#sub-category').empty();
$.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
});
}, "json");
});
});
And my fetchCategories.php
#$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
}
/// end of checking injection attack ////
require "includes/config.php";
$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result);
echo json_encode($main);

You can use localStorage to store the current value which is selected by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.
Your jquery code will somewhat look like below (Sorry for any syntax error) :
$(document).ready(function() {
//check if there is any value in localStorage
if (localStorage.getItem("save") != null) {
//get that value
var value = localStorage.getItem("save");
console.log(value);
//set value in selected box
$("#sub-category").val(value);
}
//onchange of subcategory
$('#sub-category').change(function() {
var values = $(this).val();
localStorage.clear(); //clear previous data
localStorage.setItem("save", values); //add data to storage
});
$('#category').change(function() {
var cat_id = $('#category').val();
$('#sub-category').empty();
$.get('fetchCategories.php', {
'cat_id': cat_id
}, function(return_data) {
$.each(return_data.data, function(key, value) {
$("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
});
}, "json");
});
});

Related

Cant seem to get the first dependency to run on AJAX call

I am having significant issues trying to get the AJAX to fire on this PHP code.
I can get the first field populated without issue, however the AJAX call does not seem to populate the first dependency (and therefore the second). I am an AJAX newbie (and have googled extensively) but cannot seem to crack this one.
Note that the ladb.php file runs fine.
<?php
// Include the database config file
include_once 'ladb.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body style="background: #D5DDE0">
<div class="container">
<form action="" method="post">
<div class="form-group col-md-6">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM City_Index GROUP BY country ORDER BY country ASC";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='{$row["countryid"]}'>{$row['country']}</option>";
}
}else{
echo "<option value=''>Country not available</option>";
}
?>
</select><br>
<!-- State dropdown -->
<label for="admin">Administrative Area</label>
<select class="form-control" id="admin">
<option value="">Select Administrative Area</option>
</select><br>
<!-- City dropdown -->
<label for="city">city_ascii</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
// Country dependent ajax
$("#country").on("change",function(){
var country = $(this).val();
if (countryid) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{countryid:countryid},
success:function(data){
$("#admin").html(data);
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
}else{
$('#admin').html('<option value="">Select Country</option>');
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
// state dependent ajax
$("#admin").on("change", function(){
var admin = $(this).val();
if (admin) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{admin:admin},
success:function(data){
$("#city").html(data);
}
});
}else{
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
});
</script>
The action.php file below
<?php
// Include the database config file
include_once 'ladb.php';
// Get country id through state name
$country = $_POST['country'];
if (!empty($country)) {
// Fetch state name base on country id
$query = "SELECT * FROM CityList WHERE country = {$country} GROUP BY admin_name_ascii";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['admin_id'].'">'.$row['admin_name_ascii'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif (!empty($_POST['admin'])) {
$admin = $_POST['admin'];
// Fetch city name base on state id
$query = "SELECT * FROM CityList WHERE admin_id = {$admin}";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['cityid'].'">'.$row['city_ascii'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
Any help greatly appreciated!
Thanks to #zergski I note that one of references were defined (countryid in Line 53). DevTools is my new best friend.

How can I append values through and will depend on the data from `<select>` element?

What I have tried is to use $.each to get the index and the value but I don't know how or what will I do next. I have an ajax, output is I have 3 elements where I get my data and split it to put it into other 2 elements which is a <select> and an <input> element. My goal is when I will select a data from my second <select> element, it's corresponding data will append to the <input> value or in short the data that will be filled up automatically inside my <input> element will be dependent on the data that was clicked on my <select> element.
Here is the image of what I got from the console when I split my data
Here is what I got when I did the $.each()
What my goal is each of the names linked to even numbers in my console should be inside my input element labeled "Leader" depending to it's section model which is above them (names)
Here is my whole code
function ToolsChange(element) {
let tools_controller = $(element).val();
// alert(tools_controller);
if (tools_controller) {
$.ajax({
type: "post",
url: "form_ajax_for_request.php",
data: {
"tools_cont": tools_controller
},
success: function(response) {
// alert(response);
// console.log(response);
var dataSplit = response;
var shouldSplit = dataSplit.split("#");
// alert(shouldSplit);
console.log(shouldSplit);
$('#sel_requested_section').html('');
$('#sel_requested_section').append(response);
$('#sel_requested_section').selectpicker('refresh');
// $('#request_leader').val(shouldSplit[10]);
$.each(shouldSplit, function(index, value) {
console.log(index);
console.log(value);
});
}
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Department: </label>
<select class="form-control selectpicker" name="tools_controller" data-live-search="true" onchange="ToolsChange(this)" required>
<option value="" selected disabled> Select Department </option>
<?php
$query = "SELECT * FROM tools_dept_registration";
$con->next_result();
$result=mysqli_query($con,$query);
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
echo '<option value="'. $row['dept_name'] .'">'.$row['dept_name'] . " - " . $row['name_of_controller'] .'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label> Section/Model </label>
<select name="request_dept" id="sel_requested_section" class="form-control selectpicker" data-live-search="true" required>
<option value="" selected disabled> Select Section/Model </option>
</select>
</div>
<div class="form-group">
<label> Leader </label>
<input class="form-control" id="request_leader" name="request_leader" readonly>
</div>
Here is my ajax/PHP
<?php
include("../include/connect.php");
if(isset($_POST['tools_cont'])){
$ID = $_POST['tools_cont'];
$query = "SELECT * FROM tools_dept_registration
LEFT JOIN tools_section_model_reg ON tools_section_model_reg.dept_id =
tools_dept_registration.ID WHERE dept_name = '$ID'";
$con->next_result();
$result=mysqli_query($con, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "#". '<option value="'.$row['section_model'].'">'. $row['section_model']
.'</option>' . "#" . $row['ass_leader'];
}
}
}
?>

How to post select box and not the value of select box

I have a form, I use the value to generate a dropdown list using ajax. When I post this form to database the value enters into database, but I want the actual name to be entered.
<form action='' method='post'>
<select name="region">
<option disabled selected hidden>---Select---</option>
<?php
$region_sql = "SELECT * FROM `regions`";
$region_res = mysqli_query($con, $region_sql);
if(mysqli_num_rows($region_res) > 0){
while($region_row = mysqli_fetch_array($region_res)){
echo "<option value='".$region_row[id]."'>".$region_row[region]."</option>";
}
}
?>
</select>
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-3">
<label for="city">City</label></div>
<div class="col-sm-7">
<select class="form-control" name="city" id="city" data-live-search="true">
<option>First choose a Region</option>
</select>
</div>
</div>
</div>
</form>
This array is the issue: echo "<option value='".$region_row[id]."'>".$region_row[region]."</option>
It ends up being: <option value="1">mid atlantic</option>
value being 1, 2, 3, 4, or 5 etc etc..
1 gets entered to the database, but I want mid atlantic to enter in the database.
Is there a way to do this?
thanks!
Update
I am using the Id to post it to getstate.php
ajax:
$(document).ready(function(){
$("#region").change(function()
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "getState.php",
data: dataString,
cache: false,
success: function(html)
{
$("#state").html(html);
}
});
});
});
getstate.php:
if($_POST['id']){
$region_id=$_POST['id'];
$sql= "select * from states where region_id='$region_id' ORDER BY state ASC";
$res= mysqli_query($con, $sql);
echo "<option>---Select--</option>";
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_array($res)){
echo "<option value='".$row['id']."'>".$row['state']."</option>";
}
}else{
die('there was an error running query [' . $con->error . ']');
}
}
The code works as is. I just want it to enter the name in the database and not the id number.

Selecting from menu one supposed to disable same value from menu two

I have two select box values, Sales Manager 1 and Sales Manager 2. I need to hide selected option value of Sales Manager 1 in Sales Manager 2. Both options fetch value from the db. How can I implement it?
View File :
<div class="form-group">
<label for="sales">Sales Manager 1</label>
<select name="erp_customer[manager_id]" id="manager_id" class="form-control select2" data-validation="required" data-validation-error-msg="Sales Manager is required" placeholder="Select Manager">
<option value="">Select Sales Manager</option>
<?php
foreach ($sale_manager as $mg) { ?>
<option value="<?php echo $mg->manager_id; ?>" <?php echo (!empty($customer) && $customer->manager_id == $mg->manager_id) ? 'selected' : ''; ?>><?php echo ucfirst(mb_strtolower($mg->sale_fname)); ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="sales">Sales Manager 2</label>
<select name="erp_customer[manager_id1]" id="manager_id2" class="form-control select2" data-validation="required" data-validation-error-msg="Sales Manager is required" placeholder="Select Manager">
<option value="">Select Sales Manager</option>
<?php
foreach ($sale_manager as $mg) { ?>
<option value="<?php echo $mg->manager_id; ?>" <?php echo (!empty($customer) && $customer->manager_id1 == $mg->manager_id) ? 'selected' : ''; ?>><?php echo ucfirst(mb_strtolower($mg->sale_fname)); ?></option>
<?php } ?>
</select>
</div>
Option values will be like 1, 2, 3, 4. I get the name from another table where 1="Ram" 2="ragu" so how can I hide option value 1 in sales manager 2 when it is selected. I tried this code but helps only on the first selection. Once I try to select again, only the first time selected value is getting disabled.
$('.form-control[id=manager_id]').on('change', function(e){
var thisVal = $(this).val();
$('.form-control[id=manager_id2] option').each(function(){
if(thisVal == $(this).attr('value')){
$(this).attr('disabled', 'disabled');
} else {
$(this).removeAttr('disabled');
}
})
})
My controller:
public function addcustomer(){
$data["title"] = "Add New Customer";
$data["sale_manager"] = $this->customer_model->getsales_managerlist();
load_default_template('customer/addnew',$data,$this);
echo $this->template->render("", true);
}
My model:
public function getsales_managerlist(){
$this->db->select("*")->from('erp_manager')->where("status", 1);
$query = $this->db->get();
return $query->result();
}
I think you really just need to not do an else in your loop for disabling. Just remove it by default, then set it again if the value matches. Here is a demo of the below script: https://jsfiddle.net/wf82Lc3j/
$(function(){
$(this).on('change', '.form-control[id=manager_id]', function(e){
// Get current value
var thisVal = $(this).val();
// Get the second select obj
var thatObj = $('.form-control[id=manager_id2]');
// Loop options
$.each(thatObj.children(), function(k,v){
// Just remove disabled right off the start
$(v).attr('disabled', false);
// If value equals current
if($(v).attr('value') == thisVal) {
// If not on the default select option
if(thisVal != '') {
// Disable the option
$(v).attr('disabled', true);
// If the user has already select this item before selecting from the first menu
if($(v).is(":selected")) {
// Reset the selection to default
thatObj.val('');
}
}
}
});
});
});

jQuery, JavaScript - Network Error?

I am working on building a Javascript/jQuery and AJAX website. However, while testing I am encountering the following error:
Timestamp: 6/11/2016 10:13:45 AM
Error: NetworkError: A network error occurred.
To me, the most obvious culprit would be the AJAX call made in my script; however, I tried commenting it out and still received the same error. When the website is first loaded it displays three alert boxes (selection=category&detail=test, and so on), but then the error appears and changing the selection does not trigger the alert.
Here is my main page:
<?php
include('header.php');
?>
<div id='mainContent'>
<?php /* if(!$_SESSION['admin']) {
echo "<p>You do not have permission to view this page!</p>";
} else { */
echo "<form method='post' action='addItem.php'>
<div class='form-group'>
<label>Category</label>
<select id='categorySelection' name='categorySelection'>
<option value=1>Playstation</option>
<option value=2>Wii</option>
<option value=3>Gamecube</option>
<option value=4>N64</option>
<option value=5>Other Console</option>
<option value=6>DS</option>
<option value=7>Game Boy</option>
<option value=8>Other Handheld</option>
<option value=9>DVD</option>
</select>
</div>
<div class='form-group'>
<label>Item</label>
<select id='itemSelection' name='itemSelection'>
</select>
</div>
<div class='form-group'>
<label>Condition:</label>
<select id='conditionSelection' name='conditionSelection'>
<option value=1>Acceptable</option>
<option value=2>Good</option>
<option value=3>Very Good</option>
<option value=4>New</option>
</select>
</div>
<div class='form-group'>
<label>Price: </label>
<input id='itemPrice' type='text' name='itemPrice' />
</div>
<div class='form-group'>
<label>Description: </label>
<textarea id='itemDescription' name='itemDescription'></textarea>
</div>
</form>";
// }
?>
</div>
<script>
function selectionHandler(selectedAction, selectedValue) {
var gameData = "selection=" + selectedAction + "&detail=" + selectedValue;
alert(gameData);
$.ajax({
type: 'POST',
url: 'filter.php',
data: gameData,
success: function(returnData) {
if(selectedAction == 'category') {
$('#itemSelection').html(returnData);
} if(selectedAction == 'game') {
$('#itemPrice').val(returnData)
} else {
$('itemDescription').val(returnData);
}
} // end return
}); // end ajax
} // end handler
$(document).ready(function() {
$("#categorySelection").on("change", selectionHandler('category', "test" ) ) ;
$("#itemSelection").on('change', selectionHandler('game', "test" ) );
$("#conditionSelection").on('change', selectionHandler('condition', "test" ) );
}); // end ready
</script>
<?php
include('footer.php');
?>
and my PHP
<?php
include("header.php");
$db = new pdoAccess("localhost","root","");
$selection = $_POST['selection']; // either game, category, or condition
$detail = $_POST['detail'] // either categoryID or ISBN/Item ID
if($selection == 'category') {
$products = $db->filterByCategory($detail);
$html = "";
foreach($products as $product) {
$html += "<option value={$product->upc)}>$product->title</option>";
}
return $html;
} elseif ($selection = 'game') {
return $db->getProductPrice($detail);
} else {
return $db->getCategoryDescription($detail);
}
?>
Thanks!
EDIT: It should be noted that I also tried other events such as focusout and select. Same issue.
In php string cocatinating is by dot . and use quotes also change here like this
$html .= "<option value='{$product->upc)}'>{$product->title}</option>";
Also use double == to compare here
} else if ($selection == 'game') {
Use echo in ajax instead of return

Categories

Resources