I want to list down the users according to the user_types while inserting so I created the two tables and each table has connections. Each model PHP file has a relationship function. and I created the jquery code and I created the controller function but it's not working I don't know where I making the mistake please help me to fix this problem. I attached all code I have written and the database also.
User Type Database
User Database Table
UserType Id and User Table usty_id has connections
UserType Model
<?php
namespace Asset_Management_System;
use Illuminate\Database\Eloquent\Model;
class UserType extends Model
{
public function userpermission()
{
return $this->hasMany('Asset_Management_System\UserPermission');
}
public function user()
{
return $this->hasMany('Asset_Management_System\User');
}
}
User Model
class User extends Authenticatable
{
public function usertype()
{
return $this->belongsTo('Asset_Management_System\UserType','usty_id');
}
}
Insert Form
<div class="form-group">
<label>User Type</label>
<select class="form-control select2" style="width: 100%;" id="ust_id" name="ust_id">
<option selected="selected">Select User Type</option>
#foreach($UserType as $ust)
<option value="{{$ust->id}}">{{$ust->usty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>User</label>
<select class="form-control select2" style="width: 100%;" id="user_id" name="user_id">
<option selected="selected">Select User</option>
#foreach($User as $us)
<option value="{{$us->id}}">{{$us->us_fname}} {{$us->us_lname}}</option>
#endforeach
</select>
</div>
Controller
public function show(Request $request)
{
//echo $id;
if (!$request->usty_id) {
$html = '<option value="">'.trans('global.pleaseSelect').'</option>';
} else {
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us) {
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
}
return response()->json(['html' => $html]);
}
And Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#ust_id").change(function(){
$.ajax({
url: "{{ route('WorkRequest.show') }}?usty_id=" + $(this).val(),
method: 'GET',
success: function(data) {
$('#user_id').html(data.html);
}
});
});
</script>
Route
Route::get('WorkRequest/show', 'WorkRequestController#show')->name('WorkRequest/show');
And this is the error I'm getting when I go to the form
Missing required parameters for [Route: WorkRequest.show] [URI: WorkRequest/{WorkRequest}]. (View: C:\xampp\htdocs\Asset_Management_Laravel\resources\views\layouts\main.blade.php)
Please Help me to solve this issues
This Code is working perfectly
<script type="text/javascript">
$(document).ready(function(){
// Department Change
$('#ust_id').change(function(){
// Department id
var id = $(this).val();
// Empty the dropdown
$('#user_id').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: "{{ route('WorkRequest/show') }}?usty_id=" + id,
type: 'get',
dataType: 'json',
success: function(response){
//alert(response);
$('#user_id').html(response.html);
}
});
});
});
</script>
public function show(Request $request)
{
//echo $id;
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us)
{
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
return response()->json(['html' => $html]);
}
Replace above Route with this-Route::post('workRequest/get_options','WorkRequestController#getOptions')->name('workRequest.options'); and place above the route::resource() route
And ajax code as below
$("#ust_id").change(function(){
let parameter = {'usty_id': $(this).val()};
$.ajax({
url: "{{ route('workRequest.options') }}",
method: 'POST',
data: parameter,
success: function(data) {
$('#user_id').html(data.html);
}
});
});
Add this Controller method to get options
public function getOptions(Request $request)
{
if (!$request->usty_id) {
$html = '<option value="">'.trans('global.pleaseSelect').'</option>';
} else {
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us) {
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
}
return response()->json(['html' => $html]);
}
Related
Hello everyone i need help.
I make dynamic dependent dropdown in Laravel 8, when create data it's work, but when i will edit data, dependent dropdown not selected in view edit.
My code like this,
view.blade
<label class="font-label">Provinsi</label>
<select name="prov_ktp" id="prov_ktp" class="form-control forms-input">
<option value="">Pilih Provinsi</option>
#foreach ($provinsi as $key => $prov)
<option value="{{ $key }}">{{ $prov }}</option>
#endforeach
</select>
<label class="font-label">Kota/Kabupaten</label>
<select name="kab_ktp" id="kab_ktp" class="form-control forms-input">
<option value="">Pilih Kota/Kabupaten</option>
</select>
<script>
$('#prov_ktp').change(function() {
var provinsiID = $(this).val();
if (provinsiID) {
$.ajax({
type: "GET",
url: "{{ url('get-kabupaten') }}?id_provinsi=" + provinsiID,
success: function(res) {
if (res) {
$('#kab_ktp').empty();
$('#kab_ktp').append('<option value="">Pilih Kota/Kabupaten</option>');
$.each(res, function(key, value) {
$('#kab_ktp').append('<option value="' + key + '">' + value + '</option>');
});
} else {
$('#kab_ktp').empty();
}
}
});
} else {
$('#kab_ktp').empty();
$('#kec_ktp').empty();
}
});
</script>
myController
// function display provinsi
public function showDalamNegeri() {
$provinsi = Provinsi::pluck('nama_provinsi', 'id_provinsi');
return view('data_pribadi.dalam_negeri', compact('provinsi'));
}
// function display kabupaten
public function getKabupaten(Request $request) {
$kabupaten = Kabupaten::where('id_provinsi', $request->id_provinsi)->pluck('nama_kabupaten', 'id_kabupaten');
return response()->json($kabupaten);
}
Route for display Kabupaten
Route::get('get-kabupaten', [DataPribadiController::class, 'getKabupaten'])->name('getKabupaten');
Thanks.
Sory my english is not good, I have a problem with comment input form in my program. the comment field in the process will only succeed if the filled column is the top column. if the comment field other than the above will fail. please enlighten him
this is a successfull process in first column comment
but if I write in the comment field other than the above will fail
token and field with_id same as comment column above, whereas value from barengan_id if in inspect element differ its contents. and also comment field so empty value
and this is my code
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Barengan;
use App\BarenganComment;
use App\User;
class CariBarenganCommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request,Barengan $id)
{
$data = [
'user_id' => auth()->id(),
'barengan_id' => $id->id,
'comment' => $request['comment'],
];
return BarenganComment::create($data);
}
public function destroy(Barengan $barengan_id,$id)
{
BarenganComment::destroy($id);
}
}
And this my form in view
<div id="form">
<form method="post" data-toogle="validator" class="form-horzontal">
{{ csrf_field() }}
{{method_field ('POST')}}
<input type="hidden" name="id" id="id">
<input type="hidden" name="barengan_id" value="{{$d->id}}" id="barengan_id">
<div class="styled-input">
<input class="input inputkoment" type="text" placeholder="Tulis Komentar ..." name="comment" id="comment">
<span></span>
<button type="submit" class="btn btn-default pull-right btn-custom-komen"><i class="fa fa-chevron-circle-right"></i></button>
</div>
</form>
</div>
<script src="{{asset('js/jquery-1-11-0.js')}}"></script>
<script>
function deleteComment(id) {
var popup = confirm("apakah anda yakin akan menghapus data?");
var csrf_token = $('meta[name="csrf-token"]').attr('content');
if(popup == true){
$.ajax({
url: "{{ url('caribarengancomment')}}/"+id,
type: "POST",
data: {'_method': 'DELETE','_token': csrf_token
},
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert("Opppps gagal");
}
})
}
}
$(function () {
$(document).on('submit','#form form',function (e) {
if (!e.isDefaultPrevented()) {
var barenganId = $('#barengan_id').val();
console.log(barenganId);
url = "{{ url('caribarengan')}}/" + barenganId + "/comment";
// url= '{{route('caribarengancomment.store',$d)}}';
$.ajax({
url: url,
type: "POST",
data: $('#form form').serialize(),
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert('Oops! error!');
}
});
return false;
}
});
});
</script>
and my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BarenganComment extends Model
{
protected $fillable = ['user_id','barengan_id','comment'];
public function user()
{
return $this->belongsTo(User::class);
}
public function barengan()
{
return $this->belongsTo(Barengan::class);
}
}
I am very tired these days stack here :(
you use multiple forms on page? look like id`s of inputs conflict.
try this way
<form method="post" data-toogle="validator" class="form-horzontal" data-barengan="{{$d->id}}">
...
if (!e.isDefaultPrevented()) {
var barenganId = $(this).data('barengan');
hello i want to display data of business2's data according to business1's dropdown list but on change() of business1 i got data in response but how to print it in second dropdown list using id. i didn't get response in success function. How to print options of dropdown list using Id.
I got response in mozila's firefox's console but i don't know how to return it in success and then how to print in second dropdown list.
<!-- ajax code starts here -->
<script>
$(document).on('change', 'select.Business1', function(){
var business1 = $('select.Business1 option:selected').val();
alert(business1);
var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url('client_area/select_business_sub_cat'); ?>',
sucess : function (data){
alert(1);
var abc = $('#business2').html(data);
}
});
});
</script>
<!-- ajax code ends here -->
Model function
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->db->query("select category.id,subcategory.* From category LEFT JOIN subcategory ON category.id = subcategory.category_id where category.id = '$business1'");
$row_cat1 = $result_sub_cat1->result();
$data = array(
'id' => $row_cat1['0']->id,
'name' => $row_cat1['0']->name
);
echo "<option value='" . $row_cat1['0']->id . "'>" . $row_cat1['0']->name . "</option>";
// return $this->output->set_output($data);
}
View --
<div class="form-group">
<label>Business 1</label>
<select name="txtBusiness1" id="" style="height: 30px;width: 100%;" class="Business1">
<option value=""> Select Business </option>
<?php
$result_cat1 = $this->db->query("select * from category");
$row_cat1 = $result_cat1->result();
?>
<?php foreach($row_cat1 as $item){ ?>
<option value="<?php echo $item->id; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
You have a type in your ajax call:
success : function (data) {
It's success not sucess
2 things may creating issue:
1) add double quotes in url
2) make it success instead of sucess
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url("client_area/select_business_sub_cat"); ?>', // add double quotes in url
success : function (data){ // make it success instead of sucess
alert(1);
var abc = $('#business2').html(data);
}
});
Change sucesss to success. You are using CI framework then use CI parameterized query, don't use static query it's hackable.
Give unique id to both div and select
It's better to follow MVC if you are use CI. Put your query in model with ci parameterized query.
<div class="form-group" id = 'divtxtBusiness1'>
<label>Business 1</label>
<select name="txtBusiness1" id="txtBusiness1" style="height: 30px;width: 100%;" class="Business1">
........
</select>
</div>
<div class="form-group" id = "div_Business_2">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
</div>
<script>
//$(document).on('change', 'select.Business1', function(){
// var business1 = $('select.Business1 option:selected').val();
$(document).on('change', '#txtBusiness1', function(){
var business1 = $('#txtBusiness1').val();
//alert(business1);
//var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url("client_area/select_business_sub_cat"); ?>',
success : function (data){
//alert(1);
$('#div_Business_2 #business2').remove();
$('#div_Business_2').append(data);
}
});
});
</script>
Controller :
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->xyzmodel->xyzmodelfunction($business1)
$str = '<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">';
for($i = 0 ; $i< count($result_sub_cat1) ; $i++)
{
$str .= '<option value="'.$result_sub_cat1['id'].'"> '.$result_sub_cat1['name'].' </option>';
}
$str .= '</select>';
echo $str;
// return $this->output->set_output($data);
}
Model :
don't use static query it's hackable.
class Xyzmodel extends CI_Model
{
......
public function xyzmodelfunction($business1)
{
$this->db->select(category.id,subcategory.*);
$this->db->from('category');
$this->db->join("subcategory", "category.id = subcategory.category_id", 'LEFT');
$this->db->where('category.id', $business1);
$result = $this->db->get();
return $result->result_array();
}
........
}
I will try the cascading dependent select box and input in Codeigniter with Ajax. The first step works quite well. The Securities can be easily loaded, when selecting an Account. The problem starts with the second step. So, when I try after the Security-selection to set the appropriate changeable Inputs, the Security-select will getting blocked and then nothing works. Don't understand what the problem is.
Please help me, the nasty blockage to dissolve. Thanks.
Ajax:
$(document).ready(function(){
var _form = $("#trans_form").serializeArray();
$('#amount_section').hide();
$('#quantity_section').hide();
$('#accountDrop').on('change',function(){
$("#securityDrop > option").remove();
var accountID = $(this).val();
if(accountID == '#') {return false;}
$.ajax({
data: _form,
type: "POST",
url: global_base_url + "custody/get_securities_dropdown/" + accountID,
success: function(securities) {
$.each(securities,function(id,value) {
var opt = $('<option />');
opt.val(id);
opt.text(value);
$('#securityDrop').append(opt);
});
}
});
});
$('#securityDrop').on('change',function(){
$('#amount_section').hide();
$('#quantity_section').hide();
var securityID = $(this).val();
if(securityID == '#') {return false;}
$.ajax({
data: _form,
type: "POST",
url: global_base_url + "custody/get_security_unit_ajax/" + securityID,
success: function(securUnit) {
if (securUnit == "UNIT") {
$('#quantity_section').show(300);
};
else if (securUnit == "FAMT") {
$('#amount_section').show(300);
};
}
});
});
});
Controller:
public function get_securities_dropdown($account_id){
$securities = $this->custody_model->get_security_by_account($account_id);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($securities);
}
public function get_security_unit_ajax($security_id){
$securUnit = $this->custody_model->get_security_unit($security_id);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($securUnit);
}
Model:
public function get_accounts_dropdown(){
$accounts = $this->db->select("ID as id, Account_Desc as descr")
->order_by("descr", "ASC")
->get($this->table2)->result();
$accounts_arr;
$accounts_arr['#'] = '-- Please select Account --';
foreach ($accounts as $account) {
$accounts_arr[$account->id] = $account->descr;
}
return $accounts_arr;
}
public function get_security_by_account($account_id){
if(!is_null($account_id)){
$securities = $this->db->where("a.ID_Account", $account_id)
->select("b.ID as id, b.Security_Desc as descr")
->join($this->table5 . " as b", "b.ID = a.ID_Security")
->order_by("descr", "ASC")
->get($this->table6 . " as a");
if($securities->num_rows() > 0){
$securities_arr;
foreach ($securities->result() as $security) {
$securities_arr[$security->id] = $security->descr;
}
return $securities_arr;
}
}
return;
}
View:
<?php echo form_open_multipart(site_url("custody/add_transaction_pro"), array("id" => "trans_form")) ?>
<div>
<label for="accountDrop">Account</label>
<div>
<?php echo form_dropdown('accountDrop', $account_arr, '#', 'id="accountDrop"'); ?>
</div>
</div>
<div id="security_section">
<label for="security_select">Security</label>
<div>
<select name="securityDrop" class="required" id="securityDrop">
<option value="#">-- Please select Security --</option>
</select>
</div>
</div>
<div id="quantity_section">
<label for="quantity">Quantity</label>
<div id="quantityInput">
<input type="text" id="quantity" name="quantity">
</div>
</div>
<div id="amount_section">
<label for="settl_amount">Amount</label>
<div id="amountInput">
<input type="text" id="settl_amount" name="settl_amount">
</div>
</div>
I have solved it. The error was quite simple, the unnecessary semicolons in the ajax part. The syntax is if() { } else if{ }
I have tried a lot to find the solution of how to populate the city dropdown by selecting the country in the first dropdown but i didn't understand the available solutions.I have populated the first dropdown from the database but i cant populate the second one due to the no knowledge of Ajax. Please provide the full code of ajax or jquery how to populate the second one by selecting the first Thanks.
View
<div class="form-group">
<label for="" class="col-md-4 control-label">City</label>
<div class="col-md-8 text center">
<select class="form-control" name="city" id="city">
<?php foreach($cityData as $data){
$id = $data->city_id;
$country_name =$data->city_name;
?>
<option value="<?php echo $id; ?>"><?php echo $city_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-4 control-label">Country</label>
<div class="col-md-8 text center">
<select class="form-control" class="country" name="country">
<option value="">Select Country</option>
<?php foreach($countryData as $data){
$id = $data->country_id;
$country_name =$data->country_name;
?>
<option value="<?php echo $id; ?>"><?php echo $country_name; ?></option>
<?php } ?>
</select>
</div>
</div>
Ajax Code
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "../form_controller/populate_cities",
data: { country : selectedCountry }
});.done(function(data){
$("#city").html(data);
});
});
});
</script>
Controller to Populate Cities
public function populate_cities(){
$this->load->model('cities');
$country_id = $this->input->post('country');
$data['cityData'] = $this->cities->getData($country_id);
$this->load->view('reservation_detail');
}
NOTE:I Assume you have country and city and state table
How this code working:- When page load, at that time controller index function is called and trigger a model function getCountry() and this function retrieve all the available country name and pass this to view. When country drop down value change it called a ajax function selectState(current country id) and this ajax function called a controller loadData() and this function called a model function loadData(filter type like state or city) and on that basic this model function return data. The same procedure follow for state drown change but with different java script function selectCity(state id) function and follow previous flow. Both the java script function call loadData js function for loading the data.
Java Script Code:-
function selectState(country_id){
if(country_id!="-1"){
loadData('state',country_id);
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}else{
$("#state_dropdown").html("<option value='-1'>Select state</option>");
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
function selectCity(state_id){
if(state_id!="-1"){
loadData('city',state_id);
}else{
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
function loadData(loadType,loadId){
var dataString = 'loadType='+ loadType +'&loadId='+ loadId;
$("#"+loadType+"_loader").show();
$("#"+loadType+"_loader").fadeIn(400).html('Please wait... <img src="image/loading.gif" />');
$.ajax({
type: "POST",
url: "loadData",
data: dataString,
cache: false,
success: function(result){
$("#"+loadType+"_loader").hide();
$("#"+loadType+"_dropdown").html("<option value='-1'>Select "+loadType+"</option>");
$("#"+loadType+"_dropdown").append(result);
}
});
}
Controller Functions:-
public function index()
{
$this->load->model('model');
$result['list']=$this->model->getCountry();
$this->load->view('top');
$this->load->view('index',$result);
$this->load->view('footer');
}
public function loadData()
{
$loadType=$_POST['loadType'];
$loadId=$_POST['loadId'];
$this->load->model('model');
$result=$this->model->getData($loadType,$loadId);
$HTML="";
if($result->num_rows() > 0){
foreach($result->result() as $list){
$HTML.="<option value='".$list->id."'>".$list->name."</option>";
}
}
echo $HTML;
}
Model Functions:-
function getCountry()
{
$this->db->select('id,country_name');
$this->db->from('country');
$this->db->order_by('country_name', 'asc');
$query=$this->db->get();
return $query;
}
function getData($loadType,$loadId)
{
if($loadType=="state"){
$fieldList='id,state_name as name';
$table='state';
$fieldName='country_id';
$orderByField='state_name';
}else{
$fieldList='id,city_name as name';
$table='city';
$fieldName='state_id';
$orderByField='city_name';
}
$this->db->select($fieldList);
$this->db->from($table);
$this->db->where($fieldName, $loadId);
$this->db->order_by($orderByField, 'asc');
$query=$this->db->get();
return $query;
}