creating dynamic navigation sub menu select from database using Codeigniter? - ajax

I am trying to create a menu with submenu in codeigniter using ajax I successfully created the menu but i am facing the problem while i will create a submenu. When i click the menu I check it in cosole.log its showing controller is get the details but after that i dont know why its not working. Pls any one solve this issue. thanks in advance
This is My View Area
<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">
<option value="">-- Select Submenu Menu --</option>
</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 area
$("#selectmenuid").change(function() {
var selectmenuid = $(this).val();
console.log(selectmenuid);
$.ajax({
type: "POST",
data: selectmenuid,
url: "<?= base_url() ?>Admin_Creator/SelectSubmenudropdown",
success: function(data) {
$.each(data, function(i, data) {
$('#selectsubmenu').append("<option value='" + data.submenu_id + "'>" + data.submenu_name + "</option>");
});
}
});
});
This is my Controller area
public function SelectSubmenudropdown()
{
if(isset($_POST['selectmenuid']))
{
$this->output->set_content_type("application/json")->set_output(json_encode($this->Model_Creator->getSubmenu($_POST['selectmenuid'])));
}
}
This is my Model area
public function getSubmenu(){
$this->db->select('submenu_id,submenu_name');
$this->db->from('menu,submenu');
$this->db->where('submenu.menu_id=menu.menu_id');
$this->db->where('submenu.menu_id', $selectmenuid);
return $query->result_array();
}

You have to receive $selectmenuid in your model method:
public function getSubmenu($selectmenuid){
$this->db->select('submenu_id,submenu_name');
$this->db->from('menu,submenu');
$this->db->where('submenu.menu_id=menu.menu_id');
$this->db->where('submenu.menu_id', $selectmenuid);
return $query->result_array();
}

Related

Laravel Batch Update Data Based on Checked Checkboxes Error

I have a table that has checkboxes on the left column that looks like this :
Table
What I want to try to do is assign a surveyor name using the select option in a modal to the surveyor column for all of the checked rows.
Modal
If I checked the first 4 rows of the table and then click the "Try Assign", it will only fill the last checked row (4th row), not all of the checked rows.
I think I've already used Foreach in my Controller so I don't know yet what is wrong with my code.
Result
This is my modal code :
<div class="modal fade" id="city-modal" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="CityModal"></h4>
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="CityForm" name="CityForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" id="labelname" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter City Name" maxlength="50">
</div>
</div>
<div class="form-group">
<label for="name" id="labelpopulation" class="col-sm-2 control-label">Population</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="population" name="population" placeholder="Enter City Population" maxlength="50">
</div>
</div>
<div class="form-group">
<label id="labelsurveyor" class="col-sm-2 control-label">Surveyor</label>
<div class="col-sm-12">
<select class="form-control select2" id="surveyor_id" name="surveyor_id" ">
<option value="">--Select Surveyor--</option>
#foreach($users as $surveyor)
<option value="{{ $surveyor->id }}">
{{$surveyor->name}}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save">Save changes</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
This is my JavaScript code for assigning the surveyor:
$(document).on('click', '.try-assign', function(e) {
var cityId = [];
var svrid;
$('.checkbox:checked').each(function() {
cityId.push($(this).val());
console.log(cityId);
});
if (cityId.length > 0) {
$.ajax({
type: "PUT",
url: "{{ url('try-assign') }}",
data: {
cityId,
svrid
},
dataType: "json",
success: function(res) {
$('#CityModal').html("Assign Surveyor");
$('#city-modal').modal('show');
$('#labelname').attr('hidden', true);
$('#labelpopulation').attr('hidden', true);
$('#labelsurveyor').attr('hidden', false);
$('#id').val(res.id);
$('#name').val(res.name).attr('hidden', true);
$('#population').val(res.population).attr('hidden', true);
$('#surveyor_id').val(res.surveyor_id).attr('disabled', false);
$('#surveyor_id').trigger('change');
svrid = res.surveyor_id;
}
});
} else {
alert('Please select atleast one row');
}
});
This is my tryAssign() function on the Controller :
public function tryAssign(Request $request)
{
$cityId = $request->cityId;
$svrid = $request->svrid;
foreach ($cityId as $key => $value) {
$city = City::find($value);
$city->surveyor_id = $svrid;
$city->update();
}
return Response()->json($city);
}
And, this is my route :
Route::put('try-assign', [CityController::class, 'tryAssign']);

Dropdown based on one table passing to other fields using ajax laravel

I'm having problem with regards to selected dropdown passing fields value to other input.
Basically I have one table (plans) which have id, plan_name, price. So i want to pass price to the other input.
So I expect the output that if I selected one of the choices the price will be on the price input.
blade.php
<div class="control-group">
<label class="control-label">Plan</label>
<div class="controls">
<select name="plan_id" id="plan_id" class="plan" style="width:220px">
<option value="0">Select</option>
#foreach($plans as $plan)
<option value="{{ $plan->id}}" >{{$plan->plan_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Price</label>
<div class="controls">
<input class="plan_price" type="number" name="price" id="price">
</div>
</div>
Here is the ajax i tried:
$(document).ready(function(){
$(document).on('change','.plan',function(){
//console.log("hmm its change");
var plan_id=$(this).val();
console.log(plan_id);
$.ajax({
type: 'get';
url:'{!!URL::to('findPrice')!!}',
data:{'id':plan_id},
dataType:'json',
success:function(data){
console.log("price");
console.log(data.price);
a.find('.plan_price').val(data.price);
},error:function(){
}
})
})
});
in my controller I have this function:
I dont know if this is also correct on the where part.
public function findPrice(Request $request){
$p = Plan::select('price')->where('id',$request->id)->first();
return response()->json($p);
}
Route::
Route::get('/findPrice','SubscriptionController#findPrice');

Ajax query returning correct value in console log, but not showing in the view

This is my html code.
<div class="form-group row add">
<label class="control-label col-sm-2" for="division_id">Division Name:</label>
<div class="col-sm-10">
<select name="district_id" id ="district_id" class="selectdistrict">
<option value="">--Select district--</option>
#foreach($atmdistrict as $cat)
<option value="{{$cat->id}}">{{$cat->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row add">
<label class="control-label col-sm-2" for="thana_id">Thana Name:</label>
<div class="col-sm-10">
<select name="thana_id" class="thananame" id ="thana_id" >
<option value="0" disabled="true" selected="true">Thana Name</option>
</select>
</div>
</div>
This is my ajax query for dependent dropdown.
$(document).ready(function(){
$(document).on('change','.selectdistrict',function(){
console.log("hmm its change");
var district_id=$(this).val();
console.log(district_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findThanaName')!!}',
data:{'id':district_id},
success:function(data){
console.log('success');
console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose thana</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id+'">'+data[i].name+'</option>';
console.log(data[i].name);
}
div.find('.thananame').html(" ");
// console.log( div.find('.name').html(" "));
div.find('.select').append(op);
//console.log( div.find('.select').append(op));
},
error:function(){
console.log('error');
}
});
});
});
The console log is showing no error, and is returning the correct data. However, the drop down menu is not showing any data. I can't figure out where I am going wrong.
screenshot of the program running
try to change :
div.find('.select').append(op);
by :
$("#thana_id").html(op);

insert data from dynamic inputs to database in codeigniter

everyone.
I'm beginner in CodeIgniter, I trying to insert data from dynamic input to database, I searched too much but I got nothing so far
my model is empty till now because I don't know how to insert data from dynamic inputs
This is my view
<form id="bookForm" method="post" class="form-horizontal"action="order/insert">
<div class="form-group">
<div class="col-xs-3">
<label for="customer_name">Customer :
<br>
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name" id="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</label>
</div>
<div class="col-xs-3">
<label for="invoice_number">Invoice Number :
<input type="text" class="form-control" name="invoice_number" id="invoice_number" placeholder="Invoice Number"/>
</label>
</div>
<div class="col-xs-3">
<label for="branch">Branch :
<input type="text" class="form-control" name="branch" id="branch" placeholder="Branch"/>
</label>
</div>
<div class="col-xs-3">
<label for="payment_term">Payment Term :
<br>
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term" id="payment_term">
<option id-="cash">Cash</option>
<option id-="bank">Bank</option>
<option id-="other">Other</option>
</select>
</label>
</div>
<br>
<br><br><br><hr>
<label class="col-xs-1 control-label">Product</label>
<div class="col-xs-4">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="product[0].title">
<?php
foreach($order as $row):
echo"<option value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" name="product[0].qty" placeholder="Quantity" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" name="product[0].price" placeholder="Price" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<!-- The template for adding new field -->
<div class="form-group hide" id="bookTemplate">
<div class="col-xs-4 col-xs-offset-1">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="title">
<?php
foreach($order as $row):
echo"<option value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" name="qty" placeholder="Quantity" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" name="price" placeholder="Price" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-1">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
This Jquery
<script>
$(document).ready(function() {
var titleValidators = {
row: '.col-xs-4', // The title is placed inside a <div class="col-xs-4"> element
validators: {
notEmpty: {
message: 'Product is required'
}
}
},
isbnValidators = {
row: '.col-xs-4',
validators: {
notEmpty: {
message: 'Quantity is required'
}
}
},
priceValidators = {
row: '.col-xs-2',
validators: {
notEmpty: {
message: 'Invoice Number is required'
},
numeric: {
message: 'The invoice number must be a numeric number'
}
}
},
bookIndex = 0;
$('#bookForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'product[0].title': titleValidators,
'product[0].qty': isbnValidators,
'product[0].price': priceValidators
}
})
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = $('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-book-index', bookIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="title"]').attr('name', 'product[' + bookIndex + '].title').end()
.find('[name="qty"]').attr('name', 'product[' + bookIndex + '].isbn').end()
.find('[name="price"]').attr('name', 'product[' + bookIndex + '].price').end();
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
$('#bookForm')
.formValidation('addField', 'product[' + bookIndex + '].title', titleValidators)
.formValidation('addField', 'product[' + bookIndex + '].qty', isbnValidators)
.formValidation('addField', 'product[' + bookIndex + '].price', priceValidators);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
$('#bookForm')
.formValidation('removeField', $row.find('[name="product[' + index + '].title"]'))
.formValidation('removeField', $row.find('[name="product[' + index + '].qty"]'))
.formValidation('removeField', $row.find('[name="product[' + index + '].price"]'));
// Remove element containing the fields
$row.remove();
});
});
This is my controller
function OrderNow(){
$this->load->model('Out_m');
$this->Out_m->outs();
$this->session->set_flashdata('done','Your Order Submitted Successfully');
redirect('Order', 'refresh');
}
Just validate your form input however you see necessary:
$this->load->library('form_validation');
$this->form_validation->set_rules('branch', 'Branch', 'required|trim');
Make sure your form validation doesn't fail.
if ($this->form_validation->run() === FALSE) {
// Throw some error or whatever
} else {
$form_data = array('branch'=>set_value('branch');
}
Then chuck that over to the model:
$this->Out_m->handling_function($form_data);
Once you get it over there, you can do whatever you want with it.

Laravel : Insert data into database using Bootstrap Modal

I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?
Here is the form part in blade:
<div id="myAlert" class="modal hide">
<div class="modal-header">
<button data-dismiss="modal" class="close" type="button">×</button>
<h3>Create User</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<div class="widget-content nopadding">
<form action="#" method="get" id="userForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">Name :</label>
<div class="controls">
<input class="span11" placeholder="Name" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label">Email :</label>
<div class="controls">
<input class="span11" placeholder="Email" type="email">
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input class="span11" placeholder="Enter Password" type="password">
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input class="span11" placeholder="Confirm Password" type="password">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
data-dismiss="modal" class="btn" href="#">Cancel</a>
</div>
</div>
Here is the Ajax Part :
$('#userForm').on('success.form.fv', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
action:"{{ url('/register') }}",
data: $form.serialize()
});
});
You need the submit button. Try to put this code inside your form.
<button type="submit" class="btn btn-primary">Register</button>
Problem with your current Confirm button is: 1) he don't have type=submit; 2) he is outside the form.
first of all add type="submit" to your button
secondly check your network tab in the dev tools in your browser and check the request does it go to /register or not ?
if the request is hitting /register what's the parameters ?
Change form method get to post
I answer here for ajax call
Laravel ajax internal servor 500 (internal server-error)
Your input type elements are missing name attribute
<input class="span11" placeholder="Name" name="name" type="text">
<input class="span11" placeholder="Email" name="email" type="email">
<input class="span11" placeholder="Enter Password" name="password" type="password">
<input class="span11" placeholder="Confirm Password" name ="confirm_password" type="password">
You then retrieve the content using Request or Input by passing the value of the name attribute
At first change your form method from get to post. Then add save button with id btnSave.
Ajax :
$("#btnSave").click(function(e){
e.preventDefault()
var $form = $("#userForm");
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
if(data.error){
return;
}
alert(data.success); // THis is success message
$('#myModal').modal('hide'); // Your modal Id
},
error: function (result) {
}
});
});
In controller :
public function store(Request $request)
{ try {
$inputs = $request->all();
ModelName::create($inputs);
$data = ['success' =>'Data saved successfully'];
} catch (\Exception $e) {
$data = ['error' =>$e->getMessage()];
}
return Response::json($data);
}
Form part in blade:
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" id="btnAdd">Confirm</a></div>
Ajax Part
$('#btnAdd').click(function () {
$.ajax({
url: '{{url('/register')}}',
type: 'POST',
data: $('#userForm').serialize(),
success: function (object) {
},
error: function (result) {
}
});
});

Resources