how to get the start date in date range picker? - daterangepicker

How to get the start date just like here in the picture.
that is something like this?
date:$('#reservation')daterangepicker.val.startDate()
here is the form
<form id="form4">
<div class="modal-body">
<div class="form-group">
<label>Date range:</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" class="form-control pull-right" id="reservation" name="reservation"/>
</div><!-- /.input group -->
</div><!-- /.form group -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-remove"></i> <span>Close</span></button>
<button type="submit" type="button" class="btn btn-outline"><i class="fa fa-check"></i> <span>Search</span></button>
</div>
</form>
and here is the ajax
<script type="text/javascript">
$(function () {
//Datemask dd/mm/yyyy
$("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"});
//Date range picker
$('#reservation').daterangepicker();
});
$("#form4").submit(function(){
$("#submit").prop('disabled', true);
$.ajax({
url:'{{ url('dashboard/add1') }}',
type: 'get',
data: {date:$('#reservation').daterangepicker.val.startDate()},
dataType:"json",
success: function(data){
if(!data.success)
{
alert('failed');
}
else
{
alert('success');
}
}
});
return false;
});
</script>
any replies will be appreciated. thank you.
Can't find any source in the internet regarding this. I hope it is possible.

i've sliced it
id= reservation value="2015-05-06, 2015-05-26"
data: {
startDate:$('#reservation').val().slice(0,10)+' 00:00:00',
endDate :$('#reservation').val().slice(12,22)+' 23:59:59'
},
startDate gives : 2015-05-06 00:00:00
endDate gives : 2015-05-26 23:59:59

Related

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

Delete form data after data is displayed or submission of the form

I use the same form to view details of a record that is in the database and make form submission. But an error occurs when I view a log and then register other data. In this case the new registration is registered three times in the database. And the reason this happens is that the form data is cached when I view or register a record. All the solutions I searched on the internet didn't work for me.
This is my form
<div id="form" style="display: none;" class="col-md-12">
<div class="row">
<h5 class="title">Add</h5>
<div class="float-right" style="margin-left: 80%">
<button class="btn btn-secondary" id="close_form">Close</button>
</div>
</div>
<form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fas fa-minus"></i></button>
</div>
</div>
<div class="card-body">
<fieldset disabled>
<div class="row">
<div class="form-group col-md-3">
<label for="inputCity">Código do documento:</label>
<input type="text" class="form-control" id="id_docs" name="id_docs">
</div>
<div class="form-group col-md-8">
<label for="inputCity">Status</label>
<input type="text" class="form-control" id="status" name="status">
</div>
</div>
</fieldset>
<div class="form-group">
<label>Assunto</label>
<textarea class="form-control" id="assunto" name="assunto" required></textarea>
</div>
<div class="form-group">
<label for="inputAddress2">Proveniencia</label>
<input type="text" class="form-control" id="prov" placeholder="Proveniencia" name="prov" required>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Correspondência</label>
<input type="date" class="form-control" id="corre" name="corre">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" id="img_cad" style="margin-left: 10px;">
<span class="control-label col-md-4"><b class="span_doc">File:</b></span><br><br>
<input type="file" id="image" aria-describedby="inputGroupFileAddon01" name="image">
<span id="store_image"></span>
</div><br>
<br>
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="hidden" name="hidden_id_docs" id="hidden_id_docs" />
<button type="submit" name="action_button" id="action_button" class="btn btn-warning">Save</button>
</div>
</div>
</form>
</div>
This is the function to view the details of a record on the form
$(document).on('click', '.edit', function(){
var id_scr = $(this).attr('id_scr');
$('#div_table').hide();
$.ajax({
url:"/scr/"+id_scr+"/edit",
cache: false,
dataType:"json",
success:function(html){
$('#action_button').text("Edit Data");
$('#assunto').val(html.data.assunto);
$('#prov').val(html.data.prov);
$('#corre').val(html.data.corre);
$('#status').val(html.data.descricao);
$('#cod_cadastro').val(html.data.cod_cadastro);
$('#hidden_id').val(html.data.id);
$('#hidden_id_docs').val(html.data.id_docs);
$('#id_docs').val(html.data.id_docs);
$('.title').text("Details...");
$('.span_doc').text("Alter Doc");
$('#action').val("Edit");
$('#form').show();
}
})
});
To clear the form data after viewing a record, I created thisTo clear the form data after viewing a record, I created this function:
$(document).on('click', '#close_form', function(){
$('#sample_form')[0].reset();
$('#form').hide();
$('#div_table').show();
});
And finally, this is the function for registering a new record
$('#sample_form').on('submit', function(event){
event.preventDefault();
$('.progress').show();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('scr.store') }}",
method:"POST",
data: new FormData(this),
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
alert('SUCCESSFULLY SAVED');
$('#sample_form')[0].reset();
$('#formModal').modal('hide');
location.reload(); //**This is the only way I found to clear the form after submitting the data**
}
})
}
})
You could try this method :
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
Or you could just call this method in your submit method

Laravel ajax auto populate field based on selection

I am working to solve an ajax issue I have where I am trying to auto populate an amount field based on the selection from the drop down box.
My table is layout as follows (Table name is Otheritemsmapping):
ID | Item | Amount
1 | Item 1 | Amount 1
2 | Item 2 | Amount 2
My modal in my Blade looks like this
<div class="modal fade" id="accountpayModal" tabindex="-1" role="dialog" aria-labelledby="accountpay" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="addaccountModal">Pay from Account of {{$member->first_name}} {{$member->last_name}}</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{!!Form::open(array('action' => ['AccountController#item'], 'method'=>'POST', 'class'=>'form-horizontal'))!!}
<div class="modal-body">
<input type="hidden" name="member" value="{{$member->id}}">
<label class="label-control">Item:</label>
<div class="input-group">
<div class="form-group">
<select type="text" class="selectpicker" data-sytle="select-with-transition" name="item" value="C" id="selectBox">
#foreach ($otheritems as $o)
<option value ={{$o->item}}>{{$o->item}}</option>
#endforeach
</select>
</div>
</div>
<label class="label-control">Amount:</label>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" name="amount" id="textField">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-round btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-round btn-primary">Save Changes</button>
</div>
{!!Form::close()!!}
</div>
</div>
</div>
I have the following JS in the same file as the above modal
<script>
$('#selectBox').change(function() {
var id = $(this).val();
var url = '{{ route("getPayments", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (reponse != null) {
$('textField').val(response.amount);
}
}
});
});
</script>
I have the following on the Controller for getPayments
public function getPayments($id = 0)
{
$data = Otheritemmapping::where('item', $id)->first();
return response()->json($data);
}
I have added the following to my Web.php file
Route::get('get/payments/{id}', 'MemberController#getPayments')->name('getPayments');
However when selecting an item from the dropdown ($o->item), the amount is not being populated in the Amount field.
Any help would be great,
Thanks
in your code there's some typos.
<script>
$('#selectBox').change(function() {
let id = $(this).val();
let url = '{{ route("getPayments", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#textField').val(response.amount);
}
}
});
});
</script>
hope this will solve your problem. if still there's anything wrong then check the browser developer console. let me know the error and i will update the answer for you.
you should use id as the option value as id is unique.

laravel 7 csrf token mismatch

I am using laravel 7 and default auth with ajax login & registration and bootstrap 4 modal window. But after login resend verification link and while registration shows "CSRF token Mismatch error", here is my code below:
#ajax setup#
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
//login with ajax
$(function(){
$("#loginForm").on("submit", function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var type = form.attr("method");
var data = new FormData(form[0]);
//console.log(data.response);
$.ajax({
url: url,
data: data,
type: type,
processData:false,
contentType: false,
success:function(){
//reset form data
$( '#loginForm' ).each(function(){
this.reset();
});
$('#login').modal('hide');
$(".top_header_area").load('/'+ ' .top_header_area');
//success message
toastr.success('Login Successfull <i class="fas fa-smile"></i>','Success',{
closeButton: true,
progressBar: true
});
},
error:function(xhr,status,error){
//console.log(xhr.status);
//console.log(xhr.responseJSON.message);
if(xhr.status === 403){
$('#login').modal('hide');
//reload header panel
$(".top_header_area").load('/'+ ' .top_header_area');
$('#verify').modal('show');
toastr.error(xhr.responseJSON.message,'Error',{
closeButton: true,
progressBar: true
});
}
errors = xhr.responseJSON.errors;
$.each(errors, function(key, value){
//shows error message
toastr.error(value,'Error',{
closeButton: true,
progressBar: true
});
});
},
});
});
});
//Register with ajax
$(function(){
$("#registerForm").on("submit", function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var type = form.attr("method");
var data = new FormData(form[0]);
//console.log(data.response);
$.ajax({
url: url,
data: data,
type: type,
processData:false,
contentType: false,
success:function(){
//reset form data
$( '#registerForm' ).each(function(){
this.reset();
});
$('#register').modal('hide');
//success message
toastr.success('Registration Successfull <i class="fas fa-smile"></i>','Success',{
closeButton: true,
progressBar: true
});
},
error:function(xhr,status,error){
if(xhr.status === 403){
$('#register').modal('hide');
//reload header panel
$(".top_header_area").load('/'+ ' .top_header_area');
$('#verify').modal('show');
toastr.error(xhr.responseJSON.message,'Error',{
closeButton: true,
progressBar: true
});
}
errors = xhr.responseJSON.errors;
$.each(errors, function(key, value){
//shows error message
toastr.error(value,'Error',{
closeButton: true,
progressBar: true
});
});
},
});
});
});
//request verification email
$(function(){
$("#resendLink").on("submit", function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var type = form.attr("method");
var data = new FormData(form[0]);
$.ajax({
url: url,
type: type,
data: data,
processData:false,
contentType: false,
success:function(){
$(".top_header_area").load('/'+ ' .top_header_area');
//reset form data
$( '#resendLink' ).each(function(){
this.reset();
});
$('#verify').modal('hide');
//success message
toastr.success('Verification Link Send <i class="fas fa-smile"></i>','Success',{
closeButton: true,
progressBar: true
});
},
});
});
});
when I check the network tab in the browser Request Cookie and Response Cookie value is different and I am using login, registration, resend verification link all forms are in modals in the same app.blade.php blade layout.
after login when click on "resend verification link" button form it shows "csrf token mismatch" but after refresh the page it works!
I am sending 2 ajax request from the same page....
1. login
2. resend verification link
but registration form sending 1 ajax request but again showing same error.
forms are below:
<!-- Modal -->
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="loginTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content wow fadeInUp" data-wow-delay=".3s">
<div class="modal-header">
<h5 class="modal-title" id="loginTitle"><i class="fas fa-sign-in-alt"></i> LOGIN</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body contact-form">
<form id="loginForm" action="{{ route('login') }}" method="post">
#csrf
<div class="form-group">
<input id="loginEmail" type="email" placeholder="Email Address" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" autocomplete="email" autofocus>
</div>
<div class="form-group">
<input id="LoginPassword" placeholder="Password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" autocomplete="current-password">
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input class="custom-control-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="custom-control-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
<button class="btn btn-lg btn-block text-uppercase button" type="submit">{{ __('Login') }}</button>
<hr>
#if (Route::has('password.request'))
<a class="btn btn-link link" href="#" data-dismiss="modal" data-toggle="modal" data-target="#reset">
{{ __('Forgot Your Password?') }}
</a>
#endif
<hr class="my-4">
<p>Don't have account? Register</p>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- ****** Register modal Start ****** -->
<!-- Modal -->
<div class="modal fade" id="register" tabindex="-1" role="dialog" aria-labelledby="registerTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content wow fadeInUp" data-wow-delay=".3s">
<div class="modal-header">
<h5 class="modal-title" id="registerTitle"><i class="fas fa-user-plus"></i> REGISTER</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body contact-form">
<form id="registerForm" action="{{ route('register') }}" method="post">
#csrf
<div class="form-group">
<input id="name" type="text" placeholder="Name" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" autocomplete="name" autofocus>
</div>
<div class="form-group">
<input id="username" type="text" placeholder="Username" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" autocomplete="username" autofocus>
</div>
<div class="form-group">
<input id="registerEmail" type="text" placeholder="E-mail" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" autocomplete="email" autofocus>
</div>
<div class="form-group">
<input id="registerPassword" type="password" placeholder="Password" class="form-control #error('password') is-invalid #enderror" name="password" autocomplete="new-password">
</div>
<div class="form-group">
<input id="register-password-confirm" type="password" placeholder="Confirm Password" class="form-control" name="password_confirmation" autocomplete="new-password">
</div>
<button class="btn btn-lg btn-block text-uppercase button" type="submit">{{ __('Register') }}</button>
<hr class="my-4">
<p>Already REGISTERED LOGIN</p>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- ****** Verify modal Start ****** -->
<!-- Modal -->
<div class="modal fade" id="verify" tabindex="-1" role="dialog" aria-labelledby="verifyTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content wow fadeInUp" data-wow-delay=".3s">
<div class="modal-header">
<h5 class="modal-title" id="verifyTitle"><i class="fas fa-certificate heading"></i> {{ __('Verify Your Email Address') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#if (session('resent'))
<div class="alert alert-success" role="alert">
{{ __('A fresh verification link has been sent to your email address.') }}
</div>
#endif
{{ __('Before proceeding, please check your email for a verification link.') }}
{{ __('If you did not receive the email') }},
<!-- {{ __('click here to request another') }} -->
<form id="resendLink" class="d-inline" method="POST" action="{{ route('verification.resend') }}">
#csrf
<button type="submit" class="btn btn-link p-0 m-0 align-baseline">{{ __('click here to request another') }}</button>.
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
To solve this problem you have to add "X-CSRF-TOKEN" to main layout <head></head> tag. The VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could store the token in an HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
For More details please visit CSRF Protection Laravel-docs 7.x

Cannot save value using ajax in laravel

I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());

Resources