load ajax array data into select2 dropdown format - javascript

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>

Related

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);
}
}
}

Click is not working in jQuery Ajax

I have an image with the Coupon code in Front End/Homepage of my website but when I try to click that nothing happens and click is not working.
The Html is below
<a class="coupon_click text-no-decoration" href="javascript:void(0);" id="coupon_id_<?php echo $couponBanner->getId(); ?>">
jQuery code is below
jQuery(document).ready(function () {
jQuery('.coupon_click').click(function () {
console.log('here');
jQuery.ajax({
type: 'POST',
url: '<?php echo url_for('#blog_couponClicked') ?>',
data: {videoId: <?php echo $video_id ?>, couponId: <?php echo $couponBanner->getId(); ?>},
success: function (res) {
if (res) {
window.location.href = res;
}
}
});
});
});
Hi my advise don't mess the JQuery Code and PHP and make it clean as much as possible,
<a class="coupon_click text-no-decoration" href="javascript:void(0);" c-id="coupon_id_<?php echo $couponBanner->getId(); ?>" v-id="<?php echo $video_id ?>">Click</>
jQuery(document).ready(function() {
jQuery('.coupon_click').on('click', function () {
console.log('here');
var cid= jQuery(this).attr('c-id');
var vid= jQuery(this).attr('v-id');
dataCall(vid,cid);
})
function dataCall(vId, cId){
jQuery.ajax({
type: 'POST',
url: 'your_url',
data: {videoId: vId,couponId:cId},
success: function (res) {
//do whatever you want to do
},error:function(err){
console.log(err);
}
})
}
})
hope it's what u want
<a id="coupon" class="" href="javascript:void(0);" id="coupon_id">coupon</a>
$("document").ready(function()
{
$("#coupon").click(function ()
{
sendS();
});
});
function sendS()
{
var couponID="abc123";//anythg u like
var userID="hahaha#mail.com";
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{cID:couponID,uID:userID},
success: function(data)
{
alert(data)
},
error: function ()
{
alert("Error!");
}
});
}

Need to be able to get the return string from javascript method in yii2

I am working on Yii2 and having a problem with returning the content of the javascript method to be sent when using the Html::a -hyperlink
The javascipt is in order to obtain the selected value of the checkboxes and it is outputting correctly.
<script>
function getNewPermissions() {
var permissions = '';
var rows = $(document).find('.permission');
$.each(rows, function (key, value) {
if($(value).find('input').prop('checked') == true)
permissions += value.id+'$&/';
})
permissions = permissions.substring(0, permissions.lastIndexOf("$&/"));
return permissions;
}
</script>
echo Html::a(Yii::t('app', 'Edit'), ['permissions/edit' ,'id'=> $name], [
'class' => 'btn btn-primary',
'onclick' =>'js:getNewPermissions()',
'data-method' => 'post',
'data' => [
'params' => ['newPerms'=>'js:getNewPermissions()','_csrf' => Yii::$app->request->csrfToken],
],
])
In the yii1 the value was read correctly from the params.
Just cant find any source to help get js in the params directly and the onclick does work.
in my project use another way
<a style="float:left;" class="btn btn-success" onclick="myFunction(this)"
type="<?php echo $value->id; ?>">
</a>
and use js function in end of layout
<script>
function updateSession(e)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
var pid = e.getAttribute('type');
var key = e.getAttribute('title');
var pqty = $("#id_" + key).val()
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/updatecard') ?>',
type: 'Post',
data: {
productid: pid,
key: key,
pqty: pqty,
_csrf: csrfToken
},
success: function (data) {
alert(data);
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcard') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#collapseCart").empty();
$("#collapseCart").append(data);
}
});
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcardpage') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#get_card2").empty();
$("#get_card2").append(data);
}
});
}
});
}
</script>

dependent dropdown error Undefined index: TRANCHE codeigniter

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>");
});
}
});

CActioveform enableClientValidation doesn't work

I have one form with activated clientValidation, but the JS code to validate the form has not been registered by Yii.
My form code is here:
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'login-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:function(form, data, hasError) {
if (!hasError){
str = $("#login-form").serialize() + "&ajax=login-form";
$.ajax({
type: "POST",
url: "' . Yii::app()->createUrl('/') . '",
data: str,
dataType: "json",
beforeSend : function() {
$("#login").attr("disabled",true);
},
success: function(data, status) {
if (data.authenticated) {
window.location = data.redirectUrl;
} else {
$.each(data, function(key, value) {
var div = "#"+key+"_em_";
$(div).text(value);
$(div).show();
});
$("#login").attr("disabled",false);
}
},
});
return false;
}
}',
),
));
echo $form->textField($model, 'username');
echo $form->passwordField($model, 'password');
echo TbHtml::submitButton('Login', ['id' => 'login']);
$this->endWidget();
The registered JS code is only this:
<script type="text/javascript">
/*<![CDATA[*/
jQuery('body').popover({'selector':'a[rel=popover]'});
jQuery('body').tooltip({'selector':'a[rel=tooltip]'});
/*]]>*/
</script>
I don't see, why its not working. Please help me to find the bug.
The code is from this blog post: http://tahiryasin.wordpress.com/2013/05/23/ajax-based-yii-login-form/

Categories