How to solve Laravel Post Error 403 with ajax? - ajax

I want to insert some record into database table which is using server side mode. Im using laravel 8, php version 8.0.13, database mysql.
This is my Route
use App\Http\Controllers\JabatanController;
Route::resource('jabatan', JabatanController::class, [
'names' => [
'index' => 'jabatan.list',
'store' => 'jabatan.store',
]]);
//dd($request->all());
My view
<button type="button" id="tambah-jabatan" class="btn btn-primary float-right" data-toggle="modal" data-target="#modal_tambah">
Tambah Jabatan
</button>
<!-- Modal -->
<div class="modal fade" id="modal_tambah" tabindex="-1" role="dialog" aria-labelledby="modalTambahLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalTambahLabel">Tambah Data Jabatan</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- mb -->
<div class=" mb-3">
<label for="jabatan">Jabatan</label>
<input type="text" name="jabatan" class="form-control" id="jabatan" placeholder="Masukkan Jabatan disini" value="" required>
</div>
<!-- /mb -->
</div>
<div class="modal-footer">
<button type="button" id="close" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="save-jabatan" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
My Controllers
public function store(StoreJabatanRequest $request)
{
$data = Jabatan::updateOrCreate([
'jabatan' => $request->jabatan,
]);
return response()->json($data);
}
My Model
class Jabatan extends Model
{
use HasFactory;
protected $table = "jabatans";
protected $fillable = [
'jabatan'
];
}
some ajax script in my main view
<script>
$('#save-jabatan').on('click', function() {
$.ajax({
url: "{{route('jabatan.store')}}",
type: "post",
data: {
jabatan: $('#jabatan').val(),
"_token": "{{csrf_token()}}"
},
success: function(res) {
console.log(res.data);
alert(res.text)
$('#close').click()
$('#tb_jabatan').DataTable().ajax.reload()
},
error: function(xhr) {
alert(xhr.responseJSON.text)
}
})
})
</script>
and when im check on inspect i got this error
POST http://localhost:8000/jabatan 403 (Forbidden)
there's any suggestion?

Ok, so in my case the problem is on my App\Http\Request\StoreJabatanRequest.php
class StoreJabatanRequest extends FormRequest;
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'jabatan' => 'required'
];
}

Related

Getting a modal to pop up when validation is false

I'm trying to create a page that when you click on add product button a modal pops up with a form that gets filled out.
What I'm trying to do is after you've submitted the form and there are errors then I would like for it to redirect back
and have the modal popup with the error messages.
Here is my code
My controller
public function addProduct(Product $product)
{
$validator = Validator::make(request()->all(), [
'title' => 'required'
]);
if($validator->fails())
{
return redirect()->back()->with([
'errors' => $validator->errors()
])
}
}
My blade file
<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#addProductModal">
<i class="fa fa-plus"></i> Add Product
</button>
#include('admin.product.add-product')
and this is my modal
<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addProductModalLabel">Add a Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ route('admin.product.addProduct') }}" method="post">
#csrf
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Save changes</button>
</div>
</form>
</div>
</div>
</div>
You can achieve that using sessions.
I'm using Form Requests for validation, and in my CreateCategoryRequest I added:
public function withValidator($validator)
{
if ($validator->fails()) {
\Session::flash('create_category_error', 'Create category validation failed!');
}
}
In blade:
#if (session('create_category_error'))
<script type="text/javascript">
$('#myModal').modal('show');
</script>
#endif
Yes it's that simple :P
Happy coding!
You can use this also.
<!-- Test if validation failed; hence show modal -->
#if($errors->getBag('default')->first('name') != '')
<script type="text/javascript">
$(document).ready(function(){
$("#addProductModal").modal('show');
});
</script>
#endif

how do I send an image from vuejs to laravel server for upload

this is my form
<div class="modal" id="profileModal" tabindex="-1" role="dialog" aria-labelledby="profileModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h5 class="modal-title">Upload Profile Picture</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="row">
<div class="col-6">
<label>Profile Picture</label>
<input ref="image" id="image" type="file" name="image" accept="image/*" class="form-control" style="border: none" #change="loadImage($event)">
</div>
<div class="col-6">
<img :src="this.image_file" class="uploading-image img-thumbnail" height="128" alt="Preview" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" #click="submitImage">Upload <i class="fas fa-user-plus"></i></button>
</div>
</div>
</div>
</div>
this method is triggered when I select an image so I can preview before upload, it also stores the image in a variable I have created
loadImage(e){
this.file = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.file);
reader.onload = e =>{
this.image_file = e.target.result;
};
console.log(this.file);
},
the above code works perfectly and am able to preview the image
these are my variables
formData: new FormData(),
file: null,
image_file: '',
this code handles the sending of request to the server using axios
submitImage(){
this.formData.append('image', this.file, this.file.name);
console.log(this.formData);
axios.put( '/data/profile/image',
this.formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
},
).then(function(response){
Fire.$emit('profileUpdate');
console.log(response.data);
swal.fire(
'Update',
'Profile Picture Updated Successfully',
'success'
);
})
.catch(function(error){
console.log(error.data);
});
$('#profileModal').modal('hide');
},
this is my laravel server side, an just checking if the request has a file
public function uploadImage(Request $request){
if($request->hasfile('image')){
return "Yes";
}
else{return "No";}
}
the above code returns 'NO' meaning there is no file attached to the formData
please is there anything I am not doing right?
Laravel has an issue receiving form-data from ajax requests using the HTTP VERB PUT, try the same thing using POST instead.
Links: https://github.com/laravel/framework/issues/13457

Laravel - How to Pass Parameter to return redirect

In my Laravel-5.8, I have:
public function manager_employee_goal_list($id)
{
$goal = AppraisalGoal::findOrFail($id);
$goaldetails = AppraisalGoalDetail::where('appraisal_goal_id', $id)->get();
return view('appraisal.appraisal_goals.manager_employee_goal_list')
->with('goal', $goal)
->with('goaldetails', $goaldetails);
}
public function manager_employee_goal_approve(Request $request, $id)
{
$goal = AppraisalGoal::find($id);
$goal->is_approved = 3;
$goal->line_manager_comment = $request->line_manager_comment;
$goal->save();
Session::flash('success', 'Goal is approved');
return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');
}
view : manager_employee_goal_list
<a class="btn btn-xs btn-info" data-toggle="modal" data-target="#approve{{ $goal->id }}" data-original-title="Approve">
Approve
</a>
<div class="modal fade" id="approve{{ $goal->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="{route('appraisal.appraisal_goals.manager_employee_goal_approve',['id'=>$goal->id])}}" method="post">
{{ csrf_field() }}
<div class="modal-header">
Approve Goal
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Comment</label>
<textarea rows="2" name="line_manager_comment" class="form-control" placeholder="Enter Comment here" value="{{old('line_manager_comment')}}" required data-validation-required-message="This field is required"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success btn-ok">Approve Goal</button>
</div>
</form>
</div>
</div>
</div>
route/web.php
Route::get('appraisal_goals/manager_employee_goal_list/{id?}', 'Appraisal\AppraisalGoalsController#manager_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');
Route::post('appraisal_goals/manager_employee_goal_approve/{id?}', 'Appraisal\AppraisalGoalsController#manager_employee_goal_approve')->name('appraisal.appraisal_goals.manager_employee_goal_approve');
When I submit on the modal form, it saves but couldn't redirect to:
return redirect()->route('appraisal.appraisal_goals.manager_employee_goal_list');
It displays this error
Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal_list(), 0 passed and exactly 1 expected
How do I resolve it?
Thanks
manager_employee_goal_list method expects an ID, all you have to do is to pass that ID, like so:
return redirect()->route(
'appraisal.appraisal_goals.manager_employee_goal_list',
['id' => $id]
);
Also I suggest you to either remove question mark after id in your defined route, or update arguments from your method by making them nullable
public function manager_employee_goal_list($id = null)
and of course you have to adjust code too

Vue js Laravel axios POST 500 Internal Server Error

I've just created laravel Vuejs Project using Axios for call API.
Get Api is working well but When I am going to post my data, getting Internal server error.
I am using Resourse for for controller.
I just Create Api and get data by This:
axios.get("http://localhost:8080/vuelaravel/tasks")
.then(response =>{this.tasks = response.data})
.catch(error => console.log(error.response));
vuelaravel is my project name.
Its working well. But when i am trying to post data into my database its shown 500 internal error.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Todo;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class TodoController extends Controller
{
public function index()
{
$tasks=Todo::orderBy('id', 'desc')->paginate(2);
return request()->json(200,$tasks);
}
public function create()
{
//
}
public function store(Request $request)
{
$todo=Todo::create($request->all());
if($todo){
$tasks=Todo::orderBy('id', 'desc')->paginate(2);
return request()->json(200,$tasks);
}
}
public function show(Todo $todo)
{
//
}
public function edit(Todo $todo)
{
//
}
public function update(Request $request, Todo $todo)
{
//
}
public function destroy(Todo $todo)
{
//
}
}
And My ADD.Vue
<template>
<div>
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="text" name="name" v-model="name" id="name" placeholder="Title Name" class="form-control" >
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" #click="addRecord">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
name:'',
}
},
methods:{
addRecord(){
axios.post("http://localhost:8080/vuelaravel/tasks",{
'name': this.name,
})
.then(data => console.log(data))
.catch(error => console.log(error))
}
}
}
</script>
<style scoped>
</style>
This is The Error:
app.js:285 POST http://localhost:8080/vuelaravel/tasks 500 (Internal Server Error)
at createError (app.js:699)
at settle (app.js:960)
at XMLHttpRequest.handleLoad (app.js:168)
I am using my csrf in Welcome.blade.php
<meta name="csrf-token" content="{{csrf_token()}}">
Get my data by This Api:
created(){
axios.get("http://localhost:8080/vuelaravel/tasks")
.then(response =>{this.tasks = response.data})
.catch(error => console.log(error.response));
}
Since you are using the method create in your model, please make sure you had mass assigned in your model by putting this code above.
protected $guarded = [];
please read this docs soruce
Try this
response($tasks) method
$tasks=Todo::orderBy('id', 'desc')->paginate(2);
return response($tasks);

Ajax not displaying error message itself, box only

For some reason AJAX is not passing the error message. Whatever I try to submit in my form, I get red line (error message style) but without error message init, which makes hard for me to debug. Any ideas what is causing error message not to be displayed?
My AJAX function, pointing to store method in TicketCategory controller:
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/ticket-category/store',
data: {
name: $("#frmAddTicketCategory input[name=name]").val(),
},
dataType: 'json',
$('#frmAddTicketCategory').trigger("reset");
$("#frmAddTicketCategory .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-ticket-category-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-ticket-category-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
My view:
<div class="modal fade" id="addTicketCategoryModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTicketCategory">
<div class="modal-header">
<h4 class="modal-title">
Add New Task
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-ticket-category-errors">
</ul>
</div>
<div class="form-group">
<label>
Name
</label>
<input class="form-control" id="name" name="name" type="text">
</input>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="Cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
Add New Task
</button>
</input>
</div>
</form>
</div>
</div>
</div>
Controller:
public function create()
{
return view('ticket_category/ticket_cat',[
'tickets' => TicketCategory::all()
]);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required'
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$ticket_category = TicketCategory::create([$request->name]);
return response()->json([
'error' => false,
'ticket_category' => $ticket_category,
], 200);
}
see the error issue
I think value is an array of errors for a field that is why you are not able to display the errors. Try this
$('#add-ticket-category-errors').append('<li>' + value[0] + '</li>')

Resources