updating the options of the "admin_id" select element - javascript

In my project i want to create difference admins for colleges ,departments and laboratorys , i u used Ajax for fetching data of admin id depends on the admin type input and i also use a logic in controller as the following in my controller :
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|',
'password' => 'required',
'roles' => 'required',
'admin_type'=>'required',
'admin_id'=>'required'
]);
$adminType = $request->input('admin_type');
$adminId = $request->input('admin_id');
$input = $request->all();
// $input['password'] = Hash::make($input['password']);
$user = User::create($input);
if ($adminType == 'colleges') {
$user->colleges()->attach($adminId);
} else if ($adminType == 'departments') {
$user->departments()->attach($adminId);
} else if ($adminType == 'laboratories') {
$user->laboratories()->attach($adminId);
}
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
public function getAdminId(Request $request)//for getting admin ids depends on the admin_type
{
$adminType = $request->admin_type;
$options = '';
if ($adminType == 'college') {
$colleges = College::all();
foreach ($colleges as $college) {
$options .= '<option value="'.$college->id.'" id="'.$college->id.'">'.$college->name.'</option>';
}
} elseif ($adminType == 'department') {
$departments = Department::all();
foreach ($departments as $department) {
$options .= '<option value="'.$department->id.'">'.$department->name.'</option>';
}
} elseif ($adminType == 'laboratory') {
$laboratories = Laboratory::all();
foreach ($laboratories as $laboratory) {
$options .= '<option value="'.$laboratory->id.'">'.$laboratory->name.'</option>';
}
}
return '<select name="admin_id" id="admin_id" class="form-control">'.$options.'</select>';;
}
in my route i have this for Ajax
Route::get('get/admin_id', [App\Http\Controllers\UserController::class, 'getAdminId'])->name('get.admin_id');
in my blade template
#extends('layouts.mainlayout')
#section('content')
<section class="content">
<div class="body_scroll">
<div class="block-header">
<div class="container-fluid">
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<div class="body">
<h2 class="card-inside-title" >User Registration</h2>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="POST" action="{{ route('users.store') }}">
#csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" placeholder="name" name = "name" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="email"name = "email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<div class="form-group ">
<label for="role">Roles:</label>
<select name="roles[]" id="roles" class= "form-control show-tick ms select2" multiple data-placeholder="Select Roles">
#foreach($roles as $tag)
<option value="{{$tag}}"
>{{$tag}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="admin_type">Admin Type</label>
<select name="admin_type" id="admin_type" class="form-control">
<option value="college">College</option>
<option value="department">Department</option>
<option value="laboratory">Laboratory</option>
</select>
</div>
<div class="form-group">
<label for="admin_id">Admin ID</label>
<select name="admin_id" id="admin_id" class="form-control">
<option value=""> </option>
</select>
</div>
<div>
<button class="btn btn-raised btn-primary waves-effect" onclick="this.form.submit()" type="submit">SUBMIT</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
#endsection
#section('scripts')
<script>
$(document).ready(function(){
$('#admin_type').on('change', function(){
var adminType = $(this).val();
$.ajax({
type:'GET',
url: '{{ route('get.admin_id') }}',
data: { admin_type: adminType },
success:function(data){
console.log(data);
$('#admin_id').append(data);
}
});
});
});
</script>
#endsection
and in console l got what i want like this "habtewolddf" but in the blade page the options are not coming, I dont know why it is not working any one who can help me please please???

You are appending select with another select. Try change <select> in blade file by <div> or even better - instead of .append() use .replaceWith() :
$('#admin_type').on('change', function(){
var adminType = $(this).val();
$.ajax({
type:'GET',
url: '{{ route('get.admin_id') }}',
data: { admin_type: adminType },
success:function(data){
console.log(data);
$('#admin_id').replaceWith(data); // Here
}
});
});

Related

JQuery Replace Function Did Not Work On Certain Select Dropdown

What I want to do is replace the id for every input. I have several inputs in my page.
This is the coding for some user input
<div class="row">
<div class="col">
<div class="form-group row">
<label class="col-md-2 col-form-label" for="daddr3_1">Address 3:</label>
<div class="col-md-9">
<input class="form-control" rows="1" maxlength="30" type="text" id="daddr3_1" name="daddr3[]" placeholder="Third line of address as in Identity Card (optional)">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<?php
include_once "common.php";
$common = new Common();
$countries = $common->getCountry($connection);
?>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="countryId_1">Country:</label>
<div class="col-md-5">
<select name="countryId[]" id="countryId_1" class="form-control" onchange="getStateByCountry();">
<option>Country</option>
<?php
if ($countries->num_rows > 0 ){
while ($country = $countries->fetch_object()) {
$countryName = $country->name; ?>
<option value="<?php echo $country->id; ?>"><?php echo $countryName;?></option>
<?php }
}
?>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="stateId_1">State:</label>
<div class="col-md-5">
<select name="stateId[]" id="stateId_1" class="form-control" onchange="getCityByState();getPostalByState()">
<option>State</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="cityDiv_1">City:</label>
<div class="col-md-5">
<select name="cityDiv[]" id="cityDiv_1" class="form-control">
<option value="">City</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="dpostal">Postal:</label>
<div class="col-md-5">
<select name="postalDiv[]" id="postalDiv_1" class="form-control">
<option>Postal</option>
</select>
</div>
</div>
</div>
</div>
I want to increase the _1 of the input if user add more than one item by duplicating the form.
This is the script to replace the _1 everytime user duplicate the form.
var attrs = ['for', 'id', 'name'];
function resetAttributeNames(section) {
var tags = section.find('input, label, select'), idx = section.index();
tags.each(function() {
var $this = $(this);
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx + 1)))
}
})
})
}
As you can see, in user input for country, state, city, and postal I used onchange function. I wonder if it ain't working because of the onchange function. Because the id can be replaced for Address 3 input. Only the list I mention above is not working.
This is the script of onchange function
<script>
function getStateByCountry() {
var countryId = $("#countryId_1").val();
$.post("ajax.php",{getStateByCountry:'getStateByCountry',countryId:countryId},function (response) {
var data = response.split('^');
$("#stateId_1").html(data[1]);
});
}
function getCityByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getCityByState:'getCityByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#cityDiv_1").html(data[1]);
});
}
function getPostalByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getPostalByState:'getPostalByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#postalDiv_1").html(data[1]);
});
}
function enable(){
var check = document.getElementById("check");
var btn = document.getElementById("btn");
if(check.checked){
btn.removeAttribute("disabled");
}
else{
btn.disabled = "true";
}
}
</script>
Any help is appreciated :)

Laravel 9: Redirect page window.location in javascript doesn't work when updating data

I am trying to update data in modals/pop-ups using jquery ajax. when I click the UPDATE Button, a page appears containing json data and the data has been successfully updated to the database.
{"success":true,"message":"Data Berhasil Diudapte!","data":{"id":6,"id_karyawan":"3","id_settingalokasi":"8","id_jeniscuti":"6","durasi":"3","mode_alokasi":"Berdasarkan Karyawan","tgl_masuk":null,"tgl_sekarang":null,"aktif_dari":"2022-01-02","sampai":"2022-12-31","created_at":"2022-12-15T06:21:04.000000Z","updated_at":"2022-12-21T04:09:04.000000Z"}}
with status 200 on the network
display on the network
but when double click on the data id on that network, an error appears like the following:
error when double click I don't know which url is meant in the error, so I'm quite confused about this error
this is my controller for function edit and update leave data:
//get data alokascuti
public function edit($id)
{
$alokasicuti = Alokasicuti::find($id);
return response()->json([
'success' => true,
'message' => 'Data Alokasi cuti',
'data' => $alokasicuti
]);
// dd($alokasicuti);
}
public function update(Request $request, $id)
{
$alokasicuti = Alokasicuti::find($id);
if($request->id_jeniscuti == 1)
{
$validate = $request->validate([
'id_karyawan' => 'required',
'id_settingalokasi'=> 'required',
'id_jeniscuti' => 'required',
'tgl_masuk' => 'required',
'tgl_sekarang' => 'required',
'aktif_dari' => 'required',
'sampai' => 'required',
]);
$alokasicuti->update([
'id_karyawan' =>$request->id_karyawan,
'id_settingalokasi'=> $request->id_settingalokasi,
'id_jeniscuti' =>$request->id_jeniscuti,
'durasi' =>$request->durasi,
'mode_alokasi' =>$request->mode_alokasi,
'tgl_masuk' => Carbon::parse($request->tgl_masuk)->format('Y-m-d'),
'tgl_sekarang' => Carbon::parse($request->tgl_sekarang)->format('Y-m-d'),
'aktif_dari' => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
'sampai' => Carbon::parse($request->sampai)->format('Y-m-d'),
]);
return response()->json([
'success' => true,
'message' => 'Data Berhasil Diudapte!',
'data' => $alokasicuti
]);
}else
{
$validate = $request->validate([
'id_karyawan' => 'required',
'id_settingalokasi'=> 'required',
'id_jeniscuti' => 'required',
'aktif_dari' => 'required',
'sampai' => 'required',
]);
$alokasicuti->update([
'id_karyawan' =>$request->id_karyawan,
'id_settingalokasi'=> $request->id_settingalokasi,
'id_jeniscuti' =>$request->id_jeniscuti,
'durasi' =>$request->durasi,
'mode_alokasi' =>$request->mode_alokasi,
'tgl_masuk' =>NULL,
'tgl_sekarang' =>NULL,
'aktif_dari' => Carbon::parse($request->aktif_dari)->format('Y-m-d'),
'sampai' => Carbon::parse($request->sampai)->format('Y-m-d'),
]);
return response()->json([
'success' => true,
'message' => 'Data Berhasil Diudapte!',
'data' => $alokasicuti
]);
}
}
this is the code in editallocation.blade.php along with the script:
<!-- script untuk mengambil data alokasi cuti -->
<script type="text/javascript">
$('body').on('click','.btn-editalokasi',function()
{
var id_alokasi =$(this).data('alokasi');
// console.log(id_alokasi);
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
url: "/edit-alokasi/"+id_alokasi,
type: "GET",
cache: false,
success: function (response) {
// console.log(response);
$('#id_alokasi').val(response.data.id);
$("#idjeniscuti").val(response.data.id_jeniscuti);
$("#idsettingalokasi").val(response.data.id_settingalokasi);
$("#id_karyawan").val(response.data.id_karyawan);
$("#duration").val(response.data.durasi);
$("#modealokasi").val(response.data.mode_alokasi);
// $("#tglmasuk").val(response.data.tgl_masuk);
// $("#tglsekarang").val(response.data.tgl_sekarang);
$("#datepicker-autoclosea3").val(response.data.aktif_dari);
$("#datepicker-autoclosea4").val(response.data.sampai);
}
});
});
</script>
<!-- script untuk menyimpan data update-->
<script type="text/javascript">
$(".input").click(function(e) {
e.preventDefault();
//nama variabel | id field pada form | value
var id_alokasi = $("#id_alokasi").val();
var id_settingalokasi= $("idsettingalokasi").val();
var id_jeniscuti = $("#idjeniscuti").val();
var id_karyawan = $("#id_karyawan").val();
var durasi = $("#duration").val();
var mode_alokasi = $("#modealokasi").val();
var tgl_masuk = $("#tglmasuk").val();
var tgl_sekarang = $("#tglsekarang").val();
var aktif_dari = $("#datepicker-autoclosea3").val();
var sampai = $("#datepicker-autoclosea4").val();
var token = $('meta[name="csrf-token"]').attr('content');
});
$.ajax({
url: "/updatealokasi/{$id_alokasi}",
type:"PUT",
data: {
"id":id_alokasi,
"id_settingalokasi": id_settingalokasi,
"id_jeniscuti": id_jeniscuti,
"id_karyawan": id_karyawan,
"durasi": durasi,
"mode_alokasi": mode_alokasi,
"tgl_masuk": tgl_masuk,
"tgl_sekarang": tgl_sekarang,
"aktif_dari":aktif_dari,
"sampai": sampai,
"_token": token,
},
success: function(response) {
window.location = "http://127.0.0.1:8000/alokasicuti";
$('#aid'+ response.id +' td:nth-child(1)').text(response.id_karyawan);
$('#aid'+ response.id +' td:nth-child(2)').text(response.id_jeniscuti);
$('#aid'+ response.id +' td:nth-child(3)').text(response.durasi);
$('#aid'+ response.id +' td:nth-child(4)').text(response.mode_alokasi);
$('#aid'+ response.id +' td:nth-child(5)').text(response.aktif_dari);
$('#aid'+ response.id +' td:nth-child(6)').text(response.sampai);
$(".input")[0].reset();
// $('#aid'+ response.id +' td:nth-child(1)').text(response.id_settingalokasi);
// $('#aid'+ response.id +' td:nth-child(6)').text(response.tgl_masuk);
// $('#aid'+ response.id +' td:nth-child(7)').text(response.tgl_sekarang);
},
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="modal fade" data-alokasi="{{$data->id}}" id="editalokasi" tabindex="-1" role="dialog" aria-labelledby="editalokasi" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="editalokasi">Edit Alokasi Cuti</h4>
</div>
<div class="modal-body">
<form class="input" action="/updatealokasi/{{$data->id}}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="panel-body">
<div class="col-md-6">
<input type="hidden" id="id_alokasi" name="id" value="{{$data->id}}">
<input type="hidden" name="id_settingalokasi" id="idsettingalokasi" value="{{$data->id_settingalokasi}}">
<div class="form-group col-sm">
<label for="id_jeniscuti" class="col-form-label">Kategori Cuti</label>
<select name="id_jeniscuti" id="idjeniscuti" class="form-control">
<option value="{{$data->id_jeniscuti}}" selected>{{$data->jeniscutis->jenis_cuti}}</option>
#foreach ($jeniscuti as $jenis)
<option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}</option>
#endforeach
</select>
</div>
<div class="form-group col-sm" id="idkaryawan">
<label for="id_karyawan" class="col-form-label">Karyawan</label>
<select name="id_karyawan" id="id_karyawan" class="form-control">
<option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
#foreach ($karyawan as $data)
<option value="{{ $data->id }}">{{ $data->nama }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="durasi" class="col-form-label">Durasi (Hari)</label>
<input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" readonly>
</div>
<div class="form-group">
<label for="mode_alokasi" class="col-form-label">Mode Alokasi</label>
<input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" id="modealokasi" readonly>
</div>
</div>
<div class="col-md-6">
<div class="" id="tglmulai">
<div class="form-group">
<label for="tgl_masuk" class="form-label">Tanggal Masuk</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tglnow">
<div class="form-group">
<label for="tgl_sekarang" class="form-label">Tanggal Sekarang</label>
<div class="input-group">
<input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalmulai">
<div class="form-group">
<label for="tgl_mulai" class="form-label">Aktif Dari</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalselesai">
<div class="form-group">
<label for="sampai" class="form-label">Sampai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" name="submit" value="save" id="update">Update</button>
</div>
</form>
</div>
</div>
</div>
</div>
please help me solve this problem, because I'm still new to jquery ajax and I don't know much about jquery ajax yet.

Laravel - Dynamic Input Field Failed to Submit without Displaying any Error

I have been battling with this issue for some days now. I have a project on Laravel-5.8
I have two model classes
AppraisalGoal
protected $fillable = [
'goal_type_id',
'appraisal_identity_id',
'employee_id',
'company_id',
'is_published',
'is_approved',
'weighted_score',
'employee_comment',
'line_manager_comment',
'goal_title',
'start_date',
'end_date',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
AppraisalGoalDetail
protected $fillable = [
'name',
'company_id',
'appraisal_goal_id',
'kpi_description',
'appraisal_doc',
'activity',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
Appraisal Goal is the main model
StoreAppraisalGoalRequest
class StoreAppraisalGoalRequest extends FormRequest
{
public function rules()
{
return [
'goal_title' => 'required|min:5|max:100',
'goal_type_id' => 'required',
'weighted_score' => 'required|numeric|min:0|max:500',
'start_date' => 'required',
'end_date' => 'required|after_or_equal:start_date',
'appraisal_goal_id' => 'required',
'kpi_description' => 'required|max:300',
'activity' => 'required|max:300',
];
}
}
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$identities = DB::table('appraisal_identity')->select('appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$goaltypes = AppraisalGoalType::where('company_id', $userCompany)->get();
$categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('appraisal.appraisal_goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities);
}
public function store(StoreAppraisalGoalRequest $request)
{
$startDate = Carbon::parse($request->start_date);
$endDate = Carbon::parse($request->end_date);
$userCompany = Auth::user()->company_id;
$appraisal_identity_id = AppraisalIdentity::where('company_id', $userCompany)->where('is_current',1)->value('id');
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $appraisal_identity_id;
$goal->employee_id = $request->employee_id;
$goal->weighted_score = $request->weighted_score;
$goal->goal_description = $request->goal_description;
$goal->start_date = $startDate;
$goal->end_date = $endDate;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
$goal->save();
foreach ( $request->activity as $key => $activity){
$goaldetail = new AppraisalGoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->appraisal_doc = $request->application_doc[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->company_id = Auth::user()->company_id;
$goaldetail->created_by = Auth::user()->id;
$goaldetail->created_at = date("Y-m-d H:i:s");
$goaldetail->is_active = 1;
$goaldetail->save();
}
Session::flash('success', 'Appraisal Goal is created successfully');
return redirect()->route('appraisal.appraisal_goals.index');
} catch (Exception $exception) {
Session::flash('danger', 'Appraisal Goal creation failed!');
return redirect()->route('appraisal.appraisal_goals.index');
}
}
create.blade
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">Creating My 3 + 1 Goals: <b>{{$identities->appraisal_name}}</b></h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('appraisal.appraisal_goals.store')}}">
#csrf
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Activity<span style="color:red;">*</span></th>
<th scope="col">KPI Description<span style="color:red;">*</span></th>
<th scope="col">Attachment</th>
<th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="activity[]" class="form-control activity" ></td>
<td><input type="text" name="kpi_description[]" class="form-control kpi" ></td>
<td>
<div class="custom-file">
<input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="exampleInputFile">Choose file</label>
</div>
</td>
<td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Weight:</label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Start Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="start_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> End Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="end_date" min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
javascript
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};
var numRows = $('.activity').length
if (isHod || (!isHod && numRows<3)) {
addRow();
}
});
function addRow() {
var addRow = '<tr>\n' +
' <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
' <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
' <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
' <td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
function addRemoveListener() {
$('.remove').on('click', function () {
var l =$('tbody tr').length;
if(l==1){
alert('you cant delete last one')
}else{
$(this).parent().parent().remove();
}
});
}
</script>
When I click on submit button, it did not save any record but redirected to the index page. No error indicated, even in the Browser Network.
Then, I added this before the try{} in the store function of the controller:
$data = $request->all(); print_r($data); exit;
and I got this result:
Array ( [_token] => KbnpT9MAFywHJBfVoWllKvr2ELSsRNZmWM4B5Eui [goal_type_id] => 2 [appraisal_identity_id] => 8 [goal_title] => goal title1 [goal_description] => [activity] => Array ( [0] => activity2 [1] => activity3 ) [kpi_description] => Array ( [0] => kpi description2 [1] => kpi description3 ) [weighted_score] => 20 [start_date] => 2020-02-03 [end_date] => 2020-02-29 )
But when I added
print_r($goal); exit;
after
$goal->save();
There was no result.
How do I get this sorted out?
Thank you.
sometimes some dev using try catch statement but forget to look whats wrong while the code thrown an exception. so lets change your catch statement to this for figure out whats wrong.
}catch (Exception $exception) {
dd($exception->getMessage());
Session::flash('danger', 'Appraisal Goal creation failed!');
return redirect()->route('appraisal.appraisal_goals.index');
}

Submit images using dropzone in laravel with other attributes of a form

I am trying to submit images from dropzone and other text field. but dropzone works separately how can i submit dropzone files with other data of form in controller. I need to submit form with files on button click in the controller method.
HTML Form
<form method="post" enctype="multipart/form-data" id="case-form" action="{{route('case-submit')}}">
#csrf
<div class="box-body form-element" >
<div class="row">
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Doctor</label>
<input class="form-control" type="text" name="doctor_name" id="doctor_name" required max="50">
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Upper Aligner</label>
<input class="form-control" type="number" name="upper_aligner" id="upper_aligner" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Portal</label>
<select class="form-control col-sm-10" name="portal_id" id="portal" required>
#foreach($portal as $obj)
<option value="{{$obj->id}}">{{$obj->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Patient</label>
<input class="form-control" type="text" name="patient_name" id="patient_name" required max="50">
</div>
</div>
<div class="form-group clearfix">
<div class="col-sm-12">
<label for="example-text-input" class="col-sm-10">Lower Aligner</label>
<input class="form-control" type="number" id="lower_aligner" name="lower_aligner" required>
</div>
</div>
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-12">
<div class="col-sm-4" runat="server">
<label for="exampleInputFile">File Before</label>
<label class="control-label file_before" style="display:none; color: #fc4b6c;"><i class="fa fa-times-circle-o"></i></label>
<div class="file-drop-area border dropzone clsbox" id="mydropzone">
</div>
</div>
<div class="col-sm-4" runat="server">
<div class="form-group">
<label for="exampleInputFile">File After</label>
<label class="control-label file_after" style="display:none; color: #fc4b6c;"><i class="fa fa-times-circle-o"></i></label>
<div class="file_after-drop-area border dropzone clsbox" id="fileafterdropzone">
</div>
</div>
</div>
<div class="col-sm-4">
<label for="exampleInputFile">IPR Form</label>
<div class="ipr_form-drop-area border">
<input type="file" id="ipr_form" name="ipr_form" class="ipr_form files" accept="image/*" required>
<p class="message">Drag your files here or click in this area.</p>
</div>
<img src="" id="profile-img-tag" width="200px" />
</div>
</div>
</div>
<!-- /.row -->
</div>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right">Submit Case</button>
</div>
<!-- /.box-body -->
</form>
Javascript
<script src="{{asset('public/js/dropzone.js')}}"></script>
<script>
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("div#mydropzone", {
url: "{{route('case-submit')}}",
acceptedFiles:'.stl',
addRemoveLinks: true,
autoProcessQueue:false,
params: {
_token: "{{csrf_token()}}"
},
});
var myDropzone = new Dropzone("div#fileafterdropzone", {
url: "{{route('case-submit')}}",
acceptedFiles:'.stl',
addRemoveLinks: true,
autoProcessQueue:false,
params: {
_token: "{{csrf_token()}}"
},
});
</script>
$(document).ready(function(e){
// Submit form data via Ajax
$("#case-form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '{{route('case-submit')}}',
data: new FormData(this),
dataType: 'html',
contentType: false,
cache: false,
processData:false,
success: function(response){
},
error: function(response){
}
});
});
});
</script>
Controller
public function caseSubmit(Request $request)
{
$case_number = $request->input('case_number');
$patient_name = $request->input('patient_name');
$doctor_name = $request->input('doctor_name');
$portal_id = $request->input('portal_id');
$date = date("Y-m-d H:m:s");
$user_id = Auth::id();
$caseInputData = ['patient_name' => $patient_name,
'doctor_name' => $doctor_name,
'case_number' => $case_number,
'created_at' => $date,
'user_id' => $user_id,
'portal_id' => $portal_id
];
$case = new Cases();
$case_data = $case->storePatientCase($caseInputData);
$caseId = $case_data->id;
$caseNumber = $case_data->case_number;
}
if ($caseId != null && $caseId > 0) {
$filesBefore = $request->file('file_before');
$no_of_files_attached = count($filesBefore);
$files_array = array();
foreach ($filesBefore as $fileBefore) {
$fileName = $fileBefore->getClientOriginalName();
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesBefore/' . $revisions;
$fileBefore->move($pathToStoreFile, $fileName);
$files_array[] = $fileName;
}
$filesAfter = $request->file('file_after');
$no_of_files_attached = count($filesAfter);
$afterfileArray = array();
foreach ($filesAfter as $fileAfter) {
$afterfileName = $fileAfter->getClientOriginalName();
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/filesAfter/' . $revisions;
$fileAfter->move($pathToStoreFile, $afterfileName);
$afterfileArray = $afterfileName;
}
$iprForm = $request->file('ipr_form');
$ipr_form = $iprForm->getClientOriginalName();
$pathToStoreFile = public_path() . '/cases/' . $caseNumber . '/ipr_form/' . $revisions;
$iprForm->move($pathToStoreFile, $ipr_form);
$unique_url = URL::to('/').'/'.$case_number.'/'.uniqid();
$data_array = [
'case_id' => $caseId,
'operator_id' => $request->input('operator_id'),
'upper_aligner' => $request->input('upper_aligner'),
'lower_aligner' => $request->input('lower_aligner'),
'file_before' => json_encode($files_array),
'file_after' => json_encode($afterfileArray),
'ipr_form' => $ipr_form,
'updated_at' => null,
'created_at' => $date,
'revisions' => $revisions,
'url' => $unique_url,
];
}
How can i get files in controller with other text data and submit data in database using this method caseSubmit

How do i save data from auto generated fields and associate it with a single Id?

i want to save milestones of a project which is got from auto generated fields into the database. I want to have several milestone data set obtained from the fields associated with a project id.
autogenerated fields
my form looks like:
<Form components -->
<form class="form-horizontal" role="form" action="#">
<!-- Basic inputs -->
<div class="panel panel-default">
<div class="panel-heading">
<h6 class="panel-title"><i class="icon-bubble4"></i>Set Up Milestone</h6></div>
<div class="panel-body">
<label class="col-sm-2">Project ID: </label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-10">
<select name="select" class="form-control input-lg">
<option value="opt1">Select Project Id</option>
<?php foreach ($listed_projects as $row):?>
<option value="opt2"><?php echo $row->no;?> <?php echo $row->project_name;?></option>
<?php endforeach ?>
</select>
</div>
<div class="col-sm-4">
<label style="color: #0B7C14">Select the ID Value of the project</label>
</div>
</div>
</div>
</div>
<div id="content" >
<div class="panel-body">
<label class="col-sm-2">Milestone: </label>
<div class="col-sm-10">
<div class="row" ">
<div class="col-sm-10">
<div class="">
<input name="attribute" type="text" class="form-control">
</div>
</div>
<div class="col-sm-4">
<label style="color: #0B7C14">Add the milestone</label>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-8" style="text-align: right;padding-top: 5px">
<span data-icon="" id="addfields" onclick="add_fields();"> Add field</span>
</div>
</form>
my javascript to insert fields in the #content is
<script type="text/javascript">
function add_fields() {
var d = document.getElementById("content");
d.innerHTML += '<div class="panel-body"><label class="col-sm-2">Milestone: </label><div class="col-sm-10"><div class="row" "><div class="col-sm-10"><div class=""><input type="text" class="form-control" id="attribute"></div></div><div class="col-sm-4"><label style="color: #0B7C14">Add the milestone attribute</label></div></div></div></div>';
}
</script>
How do i save this into the database? which has milestone_no, project_id, and the milestone?
Thank you in advance.
You need to pass the data first like so:
$(document).on('submit', '.form-horizontal', function(event) {
event.preventDefault(); //prevents from submitting form
$.ajax({
url: "<YOUR URL RECEIVING THE FORM DATA>",
type: "post",
dataType: 'json',
data: $(this).serialize(),
success: function(d) {
}
});
});
On your page receiving the form data, something like this:
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
$this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
$this->form_validation->set_message('xss_clean', 'Invalid characters.');
//run validation on form input
if ($this->form_validation->run() == FALSE)
{
$response['status'] = 'error';
$response['errors'] = validation_errors();
echo json_encode($response);
}
else
{
//insert your data
}

Categories

Resources