Retain ajax populated value in dropdown - javascript

I have a form where two dropdowns are kept. When the value on first is selected, ajax call is made to show related results as second dropdown list. My issue is when value is selected on second dropdown and form is submitted the second dropdown list(which is being populated on basis of first selection made in first select box) gets empty. I want to retain the value into the second dropdown selected after form submit. Can I have some insight over the same.
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Level:</label>
</div>
<div class="col-md-9">
<select name="levels" class="form-control" required="" id = "level">
<?php $fnc->selectBoxsearchLevel("tbl_levels_master","id","level_title", $level_id) ; ?>
</select>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#level").change(function() {
var level_id = $(this).val();
if(level_id != "") {
$.ajax({
url:"get_units.php",
data:{l_id:level_id},
type:'POST',
success:function(response) {
//console.log (response);
var resp = $.trim(response);
$("#unit").html(resp);
}
});
} else {
$("#unit").html("<option value=''>------- Selected --------</option>");
}
});
});
</script>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Unit:</label>
</div>
<div class="col-md-9">
<select name="units" class="form-control" required="" id= "unit">
<option>------- Select --------</option>
</select>
</div>
</div>
</div>
And my get_units.php
<?php
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$level_id = $_POST['l_id'];
$sql = "select * from tbl where level=$level_id";
$res = $db->query($sql);
echo "<option value=''>------- Select --------</option>";
while($row = mysql_fetch_array($res)) {
echo "<option value='".$row['id']."'>".$row['title']."</option>";
}
?>

Related

Select show hide div after specific values input

I'm basically trying to
Show upload div when status input valued="Tidak aktif"
Hide upload div when status input valued ="Aktif"
This is my code
<h2>EDIT STATUS PEGAWAI</h2>
<?php
$ambildata = $koneksi -> query ("SELECT * FROM diniyah WHERE ID ='$_GET[id]'");
$pecahdata = $ambildata -> fetch_assoc();
echo "<pre>" ;
print_r($pecahdata);
echo "</pre>";
?>
<h2>GANTI STATUS PEGAWAI : </h2>
<form method="post" enctype="multipart/form-data">
<select class="form-control form-control-lg" name="STATUS" id="STATUS">
<option value="Aktif">AKTIF</option>
<option value="Tidak Aktif">TIDAK AKTIF</option>
<div class="form-group" style="display:none;">
<input type="file" name="uploaddiniyah" class="form-control">
<button class="btn btn-primary" name="ubah">Konfirmasi</button>
</div>
</form>
<?php
if (isset($_POST['Tidak Aktif'])){
include'upload.php';
}else{
include'home.php';
}
?>
<?php
if (isset($_POST['ubah'])) {
$uploaddiniyah = true;
$namafoto = $_FILES ['uploaddiniyah']['name'];
$lokasifoto = $_FILES ['uploaddiniyah']['tmp_name'];
move_uploaded_file($lokasifoto, "../fotodokumen/".$namafoto);
//jk foto dirubah
$koneksi->query("UPDATE diniyah SET status='$_POST[STATUS]' WHERE ID='$_GET[id]'");
$update_gambar=mysqli_query($koneksi,"UPDATE diniyah SET uploaddiniyah='$namafoto' WHERE ID='$_GET[id]'");
echo "<div class='alert alert-info'> Data Tersimpan</div>";
}
?>
Is there a mistake on my code?
You can use basic js for do that like:
let status = document.getElementById('STATUS');
let upload = document.getElementById('upload');
status.onchange = function()
{
if(this.value === "Tidak Aktif"){
upload.style.display = 'block';
}else{
upload.style.display = 'none';
}
}
<select class="form-control form-control-lg" name="STATUS" id="STATUS">
<option value="Aktif">AKTIF</option>
<option value="Tidak Aktif">TIDAK AKTIF</option>
</select>
<div class="form-group" id='upload' style="display:none;">
<input type="file" name="uploaddiniyah" class="form-control">
</div>

Fill in radio input with database data

When I query the form returns the input radio filled with the data of the database, as shown:
<input type="radio" id="Estado" name="Estado" value="Pendente" ' . ( ($row6["Estado"]=='Pendente') ? 'checked' : '' ) .' readonly="true"> Pendente <input type="radio" id="Estado" name="Estado" value="Concluído" ' . ( ($row6["Estado"]=='Concluído') ? 'checked' : '' ) .' readonly="true"> Concluído
I also show in the completed image:
But when I click the edit button it changes the filled input radio and should not, because it no longer fills according to the data of the database, as I show in the image:
script:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
$('#Estado1').prop("checked", data.Estado);
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});
$('#insert_form6').on("submit", function(event){
event.preventDefault();
if($('#Colaborador6').val() == "")
{
alert("Colaborador é necessário");
}
else
{
$.ajax({
url:".conexao26",
method:"POST",
data:$('#insert_form6').serialize()
,
beforeSend:function(){
$('#insert6').val("Inserting");
},
success:function(data){
$('#insert_form6')[0].reset();
$('#exampleModal6').modal('hide');
$('#employee_table').html(data);
location.reload("exampleModal6");
}
});
}
});
HTML:
<form method="post" id="insert_form6">
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Data-name" class="col-form-label">Data</label></h6>
<h6><input type="date" name="data6" id="data6" value="<?php echo date("Y-m-d");?>"></h6>
</div>
</div>
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Colaborador-text" class="col-form-label">Colaborador</label></h6>
<h6><select style="width:150px" name="Colaborador6" id="Colaborador6" required>
<option></option>
<?php
$sql = "SELECT Funcionario FROM centrodb.InfoLuvas WHERE Ativo = '1' AND Funcao = 'Limpeza' AND Valencia = 'LAR'";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Funcionario'].'">'.$ln['Funcionario'].'</option>';
}
?>
</select></h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Tarefa Pendente</label></h6>
<textarea type="text" id="Observacao6" name="Observacao6" class="form-control"></textarea>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Estado</label></h6>
<div style="clear:both;"></div>
<h6><input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente <input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído</h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="disabled form-group">
<h6><label for="Observacao-name" class="col-form-label">Conclusão</label></h6>
<textarea type="text" id="Conclusao" name="Conclusao" class="form-control"></textarea>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="Nome6" id="Nome6" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="NomeConc" id="NomeConc" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Sair</button>
<input type="hidden" name="employee_id6" id="employee_id6" />
<input type="submit" name="insert6" id="insert6" value="Registo" data-toggle="modal" class="btn btn-success" />
</div>
</form>
I'm trying these ways but I still do not solve the problem:
1st form:
var tipo_conta = $('.tipo_conta').val(data.Estado);
if(tipo_conta == 'Pendente'){
$('#Estado1').prop('checked' , true);
}else{
$('#Estado2').prop('checked' ,true);
}
2st form:
var radios = document.getElementsByName("Estado");
if (radios.value == "Pendente") {
radios.checked = true;
}else{
radios.checked = true;
}
Can anyone help?
I found the issue inside the HTML file. As #daddygames suggested you have used the same ID in both Radio button. see below
<h6>
<input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente
<input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído
</h6>
An ID must be unique. Update the ID and make it unique. Then change the code in .ajax script according to your need. This will help you.
First I created the variable lis to receive the value that the radio input receives from the database:
var lis = $("#Estado").val();
Then inside the data function I created another variable with the value that the radio input receives from the function:
var teste = data.Estado;
and finally I check with if:
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
Full Code:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
var lis = $("#Estado").val();
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
var teste = data.Estado;
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});

Dropdown Onchange and Passing JavaScript Value to PHP

Hello I have a problem on how should I send a JavaScript value to PHP.
Here is my form:
Dropdown Question from database:
fiddle code
<form action="action/survey">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Select Question</label>
<div class="col-sm-10">
<select class="form-control" id="mySelect" onchange="option()">
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = $id");
while ($q = mysqli_fetch_array($sql)) {
?>
<option value="<?php echo $q[0]?>"><?php echo $q[2]?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label " for=""></label>
</div>
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = 1 AND survey_qID = 1");
$d1= mysqli_fetch_array($sql);
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Question</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $d1[2]?>">
</div>
</div>
<?php
$variable = $d1[3];
$z = 1;
$piece = explode(",", $variable);
foreach ($piece as $key => $value) {
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Option <?php echo $z?> </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $value?>">
</div>
</div>
<?php
$z++;
}
?>
<div class="text-center">
<button type="submit" class="btn btn-default" name="">Update</button>
</div>
</form>
JavaScript:
function option(){
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
What I want is if I select 1 value on the drop-down, the value of option must be sent to a PHP variable in this query:
SELECT *, (
SELECT GROUP_CONCAT(answer) AS `option`
FROM `survey_anweroptions`
WHERE survey_qID = sq.survey_qID
) `option`
FROM `survey_questionnaire`sq
WHERE sq.survey_ID = 1
AND survey_qID = (**the value of option will go here**)
You should use name instead of id. and do print_r($_POST) to check weather post data coming or not. also you dont need javascript for this until you are using ajax to call your php script
like #Coder said you the inputs send to the server with it's name attribute not id attribute
you should change the select element to
<select class="form-control" id="mySelect" name="my_select" onchange="option()">
and retrieve it's value with
$_POST['my_select'] // if you use POST method on form submition
$_GET['my_select'] // if you use GET method on form submition
$_REQUEST['my_select'] // if you accept any method

Jquery autocomplete combo box/selectbox using codeigniter

I want to ask, has someone ever created autocomplete using combo box / select box with code igniter?
I've tried but only managed to use autocomplete for 2 input text but I have another idea to create autocomplete with text combined with combo box. I've do created that but I have trouble my autocomplete in the text is successful but in the combo box does not work only show empty option. can someone help me? this is my source code
My Table : i probably using 2 table for autocomplete : 1. tb_produk and 2. tb_kategori_produk
https://imgur.com/a/xpysI | 2. https://imgur.com/a/DVgUl
My Controller : user.php
public function request_produk(){ //used for calling view
$data["kateprod"] = $this->db->where("f_status_kategori_produk","1")
->get("tb_kategori_produk")->result_array();
$this->theme->panel('user/v_request',$data);
}
public function mesin() //user for jquery called data
{
$keyword = $this->uri->segment(3);
$data = $this->db->from('tb_produk')->join('tb_kategori_produk','tb_kategori_produk.f_id_kategori_produk=tb_produk.f_kategori_produk')->like('f_nama_produk',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->f_nama_produk,
'idpro' =>$row->f_id_produk,
'idkate' =>$row->f_id_kategori_produk,
'kategori'=>$row->f_nama_kategori_produk
);
}
echo json_encode($arr);
}
My Controller : v_request.php
<div id="content">
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function() {
$(".autocomplete").autocomplete({
serviceUrl: site+"/user/mesin",
onSelect: function (suggestion) {
$("#v_idproduk").val(""+suggestion.idpro);
$("#v_kategori").val(""+suggestion.kategori);
$("#v_idkategori").val(""+suggestion.idkate);
}
});
});
</script>
<?php $id = $this->session->userdata('f_id_user');
<input type="hidden" name="dt[f_id_user]" value="<?php echo $this->session->userdata('f_id_user'); ?>">
<input type="hidden" id="v_idproduk" name="dt[f_id_produk]">
<input type="hidden" id="v_idkategori" name="dt[f_kategori_produk]">
<div class="form-group br-form"> <!-- This form group i used to autocomplete text -->
<div class="col-md-2">
<label class="control-label">Nama Mesin</label>
</div>
<div class="col-md-10">
<input type="search" class="autocomplete form-control" id="autocomplete1" name="nama_mesin" required/>
</div>
</div><br><br>
<div class="form-group br-form"> <!-- This form group i used to autocomplete combo box-->
<div class="col-md-2">
<label class="control-label">Kategori Mesin</label>
</div>
<div class="col-md-10">
<select id="v_kategori" name="dt[f_kategori_produk]" class="form-control" required>
<option value="">---Harap Pilih---</option>
<?php foreach ($kateprod as $key) { ?>
<option value="<?=$key['f_id_kategori_produk']?>" id="v_kategori"><?php echo $key["f_nama_kategori_produk"];?></option>
<?php } ?>
</select>
</div>
</div><br>
This is my demo
https://streamable.com/wvn25

AJAX call PHP same page and reload option values

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

Categories

Resources