dependent dropdown error Undefined index: TRANCHE codeigniter - javascript

i have this drop-down dependent on the choices of the other 2 drop-downs i have debugged the java script but it has an error on my error logs that says,
Undefined index: TRANCHE
here is my controller
public function dependent_dropdown()
{
if(isset($_POST['TRANCHE']) || isset($_POST['GRADE']))
{
$data = $_POST['TRANCHE'];
$data1 = $_POST['GRADE'];
$this->output
->set_content_type("application/json")
->set_output(json_encode($this->EmployeeSalary_Model->getType($data, $data1)));
}
}
and here is my javascript
jQuery(document).ready(function(){
$("#GRADE").change(function() {
var TRANCHE = {"TRANCHE" : $('#TRANCHE').val()};
var GRADE = {"GRADE" : $('#GRADE').val()};
console.log(TRANCHE);
console.log(GRADE);
$.ajax({
type: "POST",
data: (TRANCHE, GRADE),
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});
});
});
please tell me the problem and how can i debug it. thanks

You have to make an array to send both values.
var postData = [ TRANCHE , GRADE ]
$.ajax({
type: "POST",
data: JSON.stringify(postData), ////stringify is important
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});

Related

set Value of select mobius not working javascript

good afternoon, have all of you, I have this problem. I am using selectr mobius1 and when I click to edit data, the "Type of Service" field does not show me the value that it should show me.
my select is initialized like this
$selecttSE = new Selectr("#tipo_SAPIE",{});
I use this onchange so that when a product is chosen the list of services changes
$("#tipo_productoE").on('change', function() {
var tipoprod = $("#tipo_productoE option:selected").val();
var select_servapi = $("#tipo_SAPIE");
$.ajax({
url: '<?= base_url('productos/select_servicios') ?>',
type: 'get',
data: {
tipoprod: tipoprod
},
beforeSend: function(){
$selecttSE.removeAll();
},
success: function(response) {
if (response.length >2 ) {
select_servapi.attr('disabled', false);
$.each(JSON.parse(response), function(i, item) {
$selecttSE.add([{
value: item.servicioapiid,
text: item.alias+' '+item.moneda+''+item.costo}])
});
let select = $("#tipo_SAPIE").parents().children('small')[0];
$(select).empty();
$(select).html('Requerido');
$(select).addClass('badge badge-soft-danger');
} else {
select_servapi.attr('disabled', true);
}
},
});
});
And my function to get the data is this
function getProducto(idproducto) {
var idproducto = idproducto;
$.ajax({
url: '<?= base_url('productos/getProducto') ?>',
type: 'GET',
data: {
idproducto: idproducto
},
success: function(response) {
console.log(response)
$selecttSE.removeAll();
$.each(JSON.parse(response), function(i, item) {
document.getElementById("tipo_productoE").value = item.tipoproductoid;
$("#tipo_productoE").trigger('change');
$selecttSE.setValue(item.servicioapiid);
});
},
error: function(errors) {
},
});
}
Thank you for taking the time to see my post have a great afternoon and much success.

How do I update datetime field using php?

I have this function wherein I can update my input fields, I have a fetch.php that fetches data from my sql.
So this is my input fields --> [Sample Pic - Input Fields][1]
Then when I click update it returns this --> [Sample Pic - Updating Input Fields][2]
My problem is whenever I update it returns all of the data in the fields except the date and time? How can I fix this?
Below are my codes. TYVM.
<div class="col-sm-2">
<input type="datetime-local" name="date_submitted" id="date_submitted" class="form-control" placeholder="Date Submitted" style="width: 120%;" />
</div>
<script>
$(document).ready(function() {
addDocu();
function addDocu() {
var action = "select";
$.ajax({
url: success: function(data) {
alert(data);
addDocu();
}
});
} else {
alert("All Fields are Required");
}
});
$(document).on('click', '.update', function() {
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {
id: id
},
dataType: "json",
success: function(data) {
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.remarks);
}
})
"select.php",
method: "POST",
data: {
action: action
},
success: function(data) {
$('#code').val('');
$('#doc_kind').val('');
$('#date_submitted').value('');
$('#remarks').val('');
$('#action').text("Add");
$('#result').html(data);
}
});
}
$('#action').click(function() {
var docCode = $('#code').val();
var docKind = $('#doc_kind').val();
var dateSubmitted = $('#date_submitted').val();
var docRemarks = $('#remarks').val();
var id = $('#docu_id').val();
var action = $('#action').text();
if (docCode != '' && docKind != '' && dateSubmitted != '') {
$.ajax({
url: "action.php",
method: "POST",
data: {
docCode: docCode,
docKind: docKind,
dateSubmitted: dateSubmitted,
docRemarks: docRemarks,
id: id,
action: action
},
success: function(data) {
alert(data);
addDocu();
}
});
} else {
alert("All Fields are Required");
}
});
$(document).on('click', '.update', function() {
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {
id: id
},
dataType: "json",
success: function(data) {
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.remarks);
}
})
});
</script>
if(isset($_POST["id"]))
{
$output = array();
$procedure = "
CREATE PROCEDURE whereDocu(IN docu_id int(11))
BEGIN
SELECT * FROM officesectb WHERE id = docu_id;
END;
";
function convert ($rem) {
$rem = trim($rem);
return preg_replace('/<br(\s+)?\/?>/i', "\n", $rem);
}
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL whereDocu(".$_POST["id"].")";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$rem = $row["remarks"];
$output['code'] = $row["code"];
$output['doc_kind'] = $row["doc_kind"];
$output['date_submitted'] = $row['date_submitted'];
$output['remarks'] = convert($rem);
}
echo json_encode($output);
}
}
}

load ajax array data into select2 dropdown format

i have a problem with filling dropdown data from ajax script.
here's my controller:
public function ajax_get_kota($idProv='')
{
$kota = $this->data['namaKota'] = $this->registrasi_model->get_nama_kota($idProv);
echo json_encode($kota);
}
here's my model:
public function get_nama_kota($idProv='')
{
$query = $this->db->query('SELECT id_kab, nama FROM kabupaten WHERE id_prov = '.$idProv.' ORDER BY nama ASC');
return $dropdowns = $query->result();
}
and view:
<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">
<?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
<div class="col-sm-3">
<?php
$atribut_kota = 'class="form-control dropKota"';
echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
set_validation_icon('Kota');
?>
</div>
<?php if (form_error('Kota')) : ?>
<div class="col-sm-9 col-sm-offset-3">
<?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
</div>
<?php endif ?>
<script>
$(document).ready(function () {
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
data: kota,
success: function(datas){
$(".dropKota").select2({
placeholder: "Pilih Kota",
data: datas
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
</div>
what i'm trying to do here is how to pass this data that im getting from ajax:
[{"id_kab":"5103","nama":"KAB. BADUNG"},{"id_kab":"5106","nama":"KAB. BANGLI"},{"id_kab":"5108","nama":"KAB. BULELENG"},{"id_kab":"5104","nama":"KAB. GIANYAR"},{"id_kab":"5101","nama":"KAB. JEMBRANA"},{"id_kab":"5107","nama":"KAB. KARANGASEM"},{"id_kab":"5105","nama":"KAB. KLUNGKUNG"},{"id_kab":"5102","nama":"KAB. TABANAN"},{"id_kab":"5171","nama":"KOTA DENPASAR"}]
into the dropdown dropKota. those data is dynamically generated when another dropdown value is changed.
current result:
select2 requires a specific format so it can be properly displayed in dropdown
var data = [{ id: 0, text: 'enhancement' } //something like this
how do i do this?
U have to do like this :
$.ajax({
url: url,
type: "POST",
async: false,
data: {id: id},
success: function(data) {
var data_array = $.parseJSON(data);
$.each(data_array.emp, function(key, value) {
$('#Your_drop_down_id').append($('<option>', {
value: key,
text: value,
}));
});
}
});
U have to parse the data(JSON to array) and then use $.each for looping all values.
Try this:
success: function(datas){
var data = JSON.parse(datas);
var options = '<select name="dd_name"><option>Select</option>';
for(i=0; i<data.length; i++)
{
options += '<option value="'+ data.col_name +'">'+ data.col_id +'</option>';
}
options += '</select>';
$('#div_id').html(options); // where #div_id is the id of a div in which this drop down is required.
},
Change $.ajax call as below
$.ajax({
url: baseUrl,
data: kota,
dataType: "JSON",
success: function(datas){
var s= document.getElementById('<Element Id>');
s.eampty();
$.each(datas, function(index, el) {
s.options[index]= new Option(index, el);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
dataType: "JSON", will respond output of ajax call in json format.
Replace <Element Id> with element id to which you want to add data.
Full Source
<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">
<?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
<div class="col-sm-3">
<?php
$atribut_kota = 'class="form-control dropKota"';
echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
set_validation_icon('Kota');
?>
</div>
<?php if (form_error('Kota')) : ?>
<div class="col-sm-9 col-sm-offset-3">
<?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
</div>
<?php endif ?>
<script>
$(document).ready(function () {
$(".dropKota").select2({
placeholder: "Pilih Kota"
});
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
data: kota,
dataType: "JSON",
success: function(datas){
var s= document.getElementById('<Element Id>');
s.eampty();
$.each(datas, function(index, el) {
s.options[index]= new Option(index, el);
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>
</div>
Finally, i found the solution after asking here and there, so here's the solution:
JS and select2 script:
<script>
$(document).ready(function () {
$(".dropProv").on("change", function(){
var idProv = $(this).val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
var kota = [];
$.ajax({
url: baseUrl,
dataType: 'json',
success: function(datas){
//since select2 need a specific format u need to do this
var kota = $.map(datas, function (obj) {
obj.id = obj.id || obj.id_kab; // replace id_kab with your identifier
obj.text = obj.text || obj.nama // replace nama with your identifier
return obj;
});
$(".dropKota").select2({ //change dropKota into your element
placeholder: "Pilih Kota",
data: kota
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
});
});
</script>

how to display more than one result data in select2 using ajax?

i am trying to display some field data from table mysql into the select2 option but whatever i do it still shows me only one.
This is how I expected: Screenshot
Any suggestions? Thanks
in javascript file I have this code
<script type="text/javascript">
//List ajax for list product
$(".js-productList").select2({
ajax: {
url: "halaman/hal_search2ajax/productsList.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function(data){
return { results: data };
},
cache: true
},
minimumInputLength: 3,
});
</script>
my code in html
<select name='item' class=\"js-productList form-control\" required></select>
Code in productList.php
<?php
// connect to database
require('../../config/koneksi.php');
$q = $_POST['q'];
$sql = mysql_query("select id_item as id, item_name as text, item_code as code from item where item_name like '%".$q."%'");
$num = mysql_num_rows($sql);
if($num > 0){
while($data = mysql_fetch_assoc($sql)){
//I want to show the item_name and item_code
$tmp[] = $data;
}
} else $tmp = array();
echo json_encode($tmp);
?>
Something like this. Seems to be the typical parse json.
I prefer tu use $.post:
<select name='item' id="itemselect" class=\"js-productList form-control\" required></select>
var data = {
q: params.term // or the way you obtain them
}
$.post('halaman/hal_search2ajax/productsList.php', data, function(response) {
$.each(response,function(i,item){
$('#itemselect').append($('<option>', {
value: item.code,
text : item.code
}));
}
}, 'json');
with append it understand what goes into value and the text
<option value="'+value+'">'+text+'</option>
You just need to manipulate response return by ajax call using map() function
try like this
$(".js-productList").select2({
ajax: {
url: "halaman/hal_search2ajax/productsList.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function(data){
output = $.map(data, function (obj) {
obj.text = obj.text + "-" + obj.code
return obj;
});
return { results: output };
},
cache: true
},
minimumInputLength: 3,
});
Here is working example https://jsfiddle.net/6tzkLtvL/2/
I hope it will help you.

Ajax data for each

Im pretty new with javascript, so im not sure how I would do this. But basically I want to add a for loop in the ajax data: call, instead of list each item manually.
jQuery(document).ready(function()
{
var $payment = {
card: 'ajax-card',
month: 'ajax-month',
year: 'ajax-year',
cvv: 'ajax-cvv',
zip: 'ajax-zip',
phone: 'ajax-phone'
};
jQuery.each( $payment, function($key, $val)
{
jQuery('.'+$val).attr({ id: $val });
});
jQuery('#pay-bill form input[type=submit]').click(function()
{
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data:
{
card: jQuery('#'+$card+' input').val(),
month: jQuery('#'+$month+' input').val(),
year: jQuery('#'+$year+' input').val(),
cvv: jQuery('#'+$cvv+' input').val(),
zip: jQuery('#'+$zip+' input').val(),
phone: jQuery('#'+$phone+' input').val()
},
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
});
Replace the code after var $payment = {...} by the code below. I have adjusted the loop where you're assigning IDs to the elements.
var data = {};
jQuery.each( $payment, function($key, $val)
{
var $element = jQuery('.'+$val);
$element.attr({ id: $val }); //<-- This line can be removed, depending on the
// circumstances
data[$key] = jQuery('input', $element).val();
});
jQuery('#pay-bill form input[type=submit]').click(function(){
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data: data,
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
If the values you want to pass in are in a form you can use $('#myForm').serialize()
Make a variable before calling $.ajax, and make a loop to set the values.
var postData = {};
$.each($payment, function(k, v){
//postData[k] = $('#'+v+' input').val();
postData[k] = $('.'+v+' input').val();
});
$.ajax({
type: 'POST',
data: postData,
// ...
});
P.S. You don't need the loop you have (setting $('.'+$val).attr({ id: $val });), you can just do $('.'+v+' input').val(); (inside a loop).
If you want an each function that can iterate with key->value pairs, checkout underscore.js: http://documentcloud.github.com/underscore/#each
_.each({key:'value',key2:'value2'},function(value,key){
// access the key->value during each iteration
});

Categories