Using jQuery, JSON and AJAX,codeigniter to populate a submenu drop down - php

I have created a form with menu and submenu. I load the menu dropdown from database but i am facing the problem to load submenu from database using ajax,json and codeigniter pls solve my issue.. thanks in advance...
This is My view coding
<form action="" method="post" id="frm_submenu">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" id="selectsubmenu">
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="form-group">
<label class="btn btn-default btn-file">
Browse <input type="file" style="display: none;">
</label>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
This is my ajax and jquery and json coding
$( "#selectmenuid" ).change(function() {
var id = $('#selectmenuid').val();
populate_submenu(id);
});
function populate_submenu(id){
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Loading ....</option>");
$.ajax({
type: "POST",
url : "<?php echo site_url('Admin_Creator/populate_submenu')?>/"+id,
contentType:"application/json;charset=utf-8",
dataType:'json',
success:function(data){
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Select Sub Menu</option>");
$.each(data,function(i,name){
$('#selectsubmenu').append('<option value="'+data[i].submenu_id+'"'+data[name].submenu_name+'</option>');
});
}
});
}
This is my controller coding
public function populate_submenu($id){
$smid=$id;
$data['query']= $this->db->select("select * from submenu where menu_id='$smid'");
echo json_encode($data);
}

You had an error when structuring your item html with appends. Use this instead:
$.each(data,function(key,value){
$('#selectsubmenu').append('<option value="'+value.submenu_id+'">'+value.submenu_name+'</option>');
});

You have a few problems at a first view. First your $smid variable should be in double quotes or escaped corespondingly. Variables in single quotes are treated as they look so your php code should look like this:
public function populate_submenu($id){
$smid=$id;
$data['query']= $this->db->select('select * from submenu where menu_id="$smid"');
echo json_encode($data);
}
In your JS code you are not closing the > from the starting open <option> tag in the each() method and getting the submenu_name wrong, you should get it by the index, so:
$('#selectsubmenu').append('<option value="' + data[i].submenu_id + '"' + data[name].submenu_name + '</option>');
should be:
$('#selectsubmenu').append('<option value="' + data[i].submenu_id + '">' + data[i].submenu_name + '</option>');
The code should be:
$("#selectmenuid").change(function() {
var id = $('#selectmenuid').val();
populate_submenu(id);
});
function populate_submenu(id) {
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Loading ....</option>");
$.ajax({
type: "POST",
url: "<?php echo site_url('Admin_Creator/populate_submenu')?>/" + id,
contentType: "application/json;charset=utf-8",
dataType: 'json',
success: function(data) {
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Select Sub Menu</option>");
$.each(data, function(i, name) {
$('#selectsubmenu').append('<option value="' + data[i].submenu_id + '">' + data[i].submenu_name + '</option>');
});
}
});
}

Related

How can I retrieve data from database whenever I select an option in drop down list in laravel?

How to set value to customerNumber(field from Marketing table) from database when I select an option from Request Number drop down list?
<div class="col-sm-2">
<label class="label" for="request_id">Request Number:</label>
<select class="form-control option" id="request_id">
<option >0 - Request Number</option>
#foreach ($customer_requests as $customer_request)
<option value={{$customer_request->id}}>{{$customer_request->id}} -{{$customer_request->requestNumber}} </option>
#endforeach
</select>
</div>
<div class="col-sm-2">
<label class="label" for="customerNumber" >Customer Number:</label>
<input type="text" class="form-control text" id="customerNumber" name="customerNumber">
</div>
I am a learner of laravel and I want to know should jQuery be used or not? And how?
<script>
$("#request_id").on({
click: function() {
}, keypress: function() {
$( this ).addClass( "inside" );
var val = $(this).val();
var data = Marketing::find(val);
$("#customerNumber").attr("value", data[customerNumber] );
}
});
</script>
for the jquery you can try like this one:
$('#request_id').change(function() {
var req_id= $(this).val();
$.ajax({
url:'{{url('/get/ref')}}/'+req_id,
method:'GET',
contentType: false,
processData: false,
success:function(result){
$("#customerNumber").val(result);
}
});
});
then, create a new controller to return customerNumber. something like:
public function customerNumber($req_id = 0){
$data = Marketing::find($req_id);
return $data->customerNumber;
}

ajax select data with multiple related data

i want to show checkbox looping from db, if i try to select data id_kendaraan in field then show the data from that id.
this my view code:
<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Tambah Pemeliharaan</h3>
</div>
<form class="form-horizontal" method="post" action="<?php echo base_url()?>Data/Pemeliharaan/Tambah">
<div class="modal-body">
<div class="form-group">
<label class="control-label col-xs-3">Nama Kendaraan</label>
<div class="col-xs-8">
<select class="form-control" name="id_kendaraan" id="id_kendaraan" required>
<option>Pilih Kendaraan</option>
<?php
if(!empty($kendaraan_)) {
foreach ($kendaraan_ as $isi) {
?>
<option value="<?php echo $isi['id_kendaraan']?>"><?php echo $isi['nama']?> - <?php echo $isi['platno']?></option>
<?php }} ?>
</select>
</div>
</div>
<?php
$index =0;
foreach ($subkriteria_ as $kr_key => $kriteria) {
?>
<div class="form-group">
<label class="control-label col-xs-3"><?php echo $kriteria['nama_kriteria'] ?></label>
<div class="col-xs-8">
<input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
<input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
<?php if(!empty($kriteria['sub'])) { ?>
<select class="form-control" name="isi_kriteria[]" required>
<option>Pilih Sub Kriteria</option>
<?php $no = 1; foreach ($kriteria['sub'] as $data) { ?>
<option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?> - <?php echo $data['value'] ?></option>
<?php $no++; } ?>
</select>
<?php } else if($kriteria['link']=='tahun_beli') { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="text" placeholder="Isi Kriteria..." readonly required>
<?php } else { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="number" placeholder="Isi Kriteria..." required>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="form-group">
<label class="control-label col-xs-3"></label>
<div class="col-xs-8">
<ul id="sparepartList" style="list-style-type: none; padding: 0;"></ul>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$('#sparepartList').empty(); // clear all sparepart checkboxes
$.each(data, function(id_kendaraan, tahun_beli, id_jenis){
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
$.each(data.spareparts, function (key, value) {
let li = $('<li><input type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '" />' +
'<input type="text" name="sparepart" value="' + value.sparepart + '" /></li>');
$('#sparepartList').append(li);
});
});
}
});
return false;
});
});
</script>
my controller:
function GetKendaraanById(){
$id_kendaraan=$this->input->post('id_kendaraan');
$data=$this->PemeliharaanModel->GetById($id_kendaraan);
echo json_encode($data);
}
i get data from view $id_kendaraan for my parameter.
this my model:
function GetById($id_kendaraan){
$this->db->select('*');
$this->db->from('tb_kendaraan');
$this->db->where('tb_kendaraan.id_kendaraan',$id_kendaraan);
$query_kendaraan = $this->db->get();
$hasil = false;
if($query_kendaraan->num_rows() > 0)
{
$data_kendaraan = $query_kendaraan->row();
$hasil = [
'tahun_beli' => $data_kendaraan->tahun_beli,
'id_jenis' => $data_kendaraan->id_jenis,
'spareparts' => [] // empty array, to be filled with spareparts data
];
$this->db->select('*');
$this->db->from('tb_sparepart');
$this->db->where('tb_sparepart.id_jenis', $data_kendaraan->id_jenis);
$query_sparepart = $this->db->get();
foreach ($query_sparepart->result() as $data_sparepart) {
$spareparts = [
'id_sparepart' => $data_sparepart->id_sparepart,
'sparepart' => $data_sparepart->sparepart,
];
array_push($hasil['spareparts'], $spareparts);
}
}
return $hasil;
}
but if i try this code, field tahun_beli, id jenis is success to showing in the view. but the checkbox from sparepart is looping exaggerated.
i try the json, the data is correct, show tahun_beli, id_jenis, is show and sparepart is show by id_jenis
but in view i try this code... tahun_beli and id_jenis is correct show one data, but sparepart is looping 3 times.. sparepart should be show data 1 times...
I checked your code and I think the issue is at this one:
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$('#sparepartList').empty(); // clear all sparepart checkboxes
$.each(data, function(id_kendaraan, tahun_beli, id_jenis){
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
$.each(data.spareparts, function (key, value) {
let li = $('<li><input type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '" />' +
'<input type="text" name="sparepart" value="' + value.sparepart + '" /></li>');
$('#sparepartList').append(li);
});
});
}
});
return false;
});
});
</script>
try to remove the first $.each, your code would be like this
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$('#sparepartList').empty(); // clear all sparepart checkboxes
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
$.each(data.spareparts, function (key, value) {
let li = $('<li><input type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '" />' +
'<input type="text" name="sparepart" value="' + value.sparepart + '" /></li>');
$('#sparepartList').append(li);
});
}
});
return false;
});
});
</script>
Hopefully it works

AJAX Request not working in Laravel 5.8.33

I am trying to make a dependent select field but When I select the first field Nothing happen to the other field. I think the ajax code is not working because I use an alert in the starting of the function call by ajax and alert didn't appear but still I am not sure what's the problem. What's wrong with my code can anyone help me in solving this problem.
Html code
<form method="POST" action="{{url('search')}}">
#csrf
<div class="input-group col-sm-10 mt-5 offset-sm-1">
<select class="form-control" name="city">
<option value="none">---Choose City---</option>
<?php foreach ($result['city_data'] as $city) {
?>
<option value="<?php echo $city->id;?>"> <?php echo $city->name;?> </option>
<?php } ?>
</select>
<select class="form-control" name="area">
<option>Choose City</option>
</select>
<div class="input-group-append">
<input type="submit" class="btn searchbutton" value="Search" name="search_button">
</div>
</form>
Ajax code
<script type="text/javascript">
$(document).ready(function() {
$('select[name="city"]').on('change', function(e) {
var cityID = $(this).val();
if(cityID) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }})
e.preventDefault();
$.ajax({
url: '/myform/ajax/'+cityID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="area"]').empty();
$.each(data, function(key, value) {
$('select[name="area"]').append('<option value="'+ key +'">'+value+'</option>');
});
}
});
}
else{
$('select[name="area"]').empty();
}
});
});
</script>
web.php
Route::get('myform/ajax/{id}','services4uController#myformAjax');
Controller.php
public function myformAjax($id)
{
echo "<script>alert('Code reached to this stage');</script>";
$area = DB::table("area")
->where("id_city",$id)
->lists("name","id");
return json_encode($area);
}

Ajax code only working on first <li>

I have the following code:
<ul class='app-tasks'>
<li class='app-tasks__item'>
<label class='app-tasks__label'>
<input id='some' value='1' type='checkbox'/>
<span>One</span>
<div class='app-tasks__mark'></div>
</label>
</li>
<li class='app-tasks__item'>
<label class='app-tasks__label'>
<input id='some' value='2' type='checkbox'/>
<span>TWO</span>
<div class='app-tasks__mark'></div>
</label>
</li>
<li class='app-tasks__item'>
<label class='app-tasks__label'>
<input id='some' value='3' type='checkbox'/>
<span>Three</span>
<div class='app-tasks__mark'></div>
</label>
</li>
</ul>
The li are being taken from MySQL. The code below is used to delete it.
$('#some').change(function() {
if ($(this).is(':checked')) {
var id = $(this).val();
var dataString2 = 'id=' + id;
console.log(id);
$.ajax({
type: "GET",
url: "sub.php",
data: dataString2,
success: function() {
console.log("Okay");
var s = $('.app-tasks .app-tasks__item').length - 1;
$('.app-header__title').html('All Tasks (' + s + ')');
}
});
return false;
}
});
But the code is only being run on the first li. There is no problem with the PHP script.
Identifiers in HTML must be unique. Switch to CSS class to identify elements using Class Selector
<input class="some" value="1" type="checkbox"/>
Then use
$('.some').change(function() {
//Rest of the code
});
You can't use the same id twice. Name each one differently, or use classes instead and do:
$('.some').change(function()
{
});

Removing dynamic dropdown options after JQuery AJAX request

I have a form that includes a dropdown box. This dropdown's options are filled dynamically, using PHP, from my database. When my form is submitted, the row containing the ticketId selected in the dropdown is removed from the database. What I would like is for, after the AJAX call is successful, have this list repopulate without the row that was just removed.
my form:
<form name="transferTicketForm" id="transferTicketForm">
<div class='form-group'>
<label for="ticket_number">Choose ticket:</label>
<select name="ticket_number" id="ticket_number" class="form-control">
<?php foreach ($assigned_tickets as $ticket): ?>
<option value="<?php echo($ticket->ticketId); ?>"><?php echo ($ticket->ticketId . " - " . $ticket->headline); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="assignTo">Transfer to:</label>
<select name="assignTo" id="assignedTo" class="form-control">
<?php foreach($employees as $employee): ?>
<option value='<?php echo($employee->userId); ?>'><?php echo ($employee->firstName . " " . $employee->lastName);?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="transferComment">Comment:</label>
<textarea name="transferComment" id="transferComment" class="form-control"></textarea>
</div>
<div class="text-center">
<input class="btn btn-primary" type="button" id="doTransferTicketButton" value="Transfer Ticket">
</div>
</form>
my Ajax call:
$('#doTransferTicketButton').click(function(){
$.ajax({
type:'POST',
url:'<?php echo site_url();?>ticket_system/transfer_and_comment_ticket',
data:{
'assigned': $('#assignedTo').val(),
'comment': $('#transferComment').val(),
'ticketId': $('#ticket_number').val()
},
success: function(data){
$target_ticket = $('#ticket_number').val();
$('#ticket_' + $target_ticket).remove();
$('#assigned').empty();
$('#transferTicketOptions').slideToggle();
}
});
});
Things I have tried:
success: function(data){
$target_ticket = $('#ticket_number').val();
$('#ticket_' + $target_ticket).remove();
$('#ticket_number').empty();
$('#transferTicketOptions').slideToggle();
}
and
success: function(data){
$target_ticket = $('#ticket_number').val();
$('#ticket_' + $target_ticket).remove();
$('#ticket_number')[0].reset();
$('#transferTicketOptions').slideToggle();
}
Neither of which work for what I'm trying to do.
Any help would be greatly appreciated. Thank you!
First make your AJAX-file echo the ticket ID when removed. This ID will be passed to the success function. And on successs run:
success: function(data){
$("#ticket_number option[value=data]").remove();
}
The code is not testet, but i think it would work.

Categories