I try to store comments about clients in admin panel.
I get error 405 (Method not allowed) when sending ajax request in Laravel 5.5
And everything works fine when I send data using html form without ajax.
Ajax:
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
}
});
$(".save-comment").click(function(e) {
e.preventDefault();
var id = $("#hidden-id").val();
var type = $("#slect-comment-type option:selected").val();
var text = $("#comment").val();
console.log(id);
console.log(type);
console.log(text);
$.post("storeComment", { id: id, type: type, text: text })
.done(function(data) {
console.log(data);
alert("Success");
$("#add-comment").css("display", "none");
})
.fail(function() {
alert("Fail");
});
});
I pass correct data in { id: id, type: type, text: text } as I see in Console.
Route:
Route::post('/comments/store' , 'CommentController@store')->name('storeComment');
CommentController:
public function store(Request $request) {
$id = $request->input('id');
$type = $request->input('type');
$text = $request->input('text');
$comment = new Comment();
$comment->client_id = $id;
$comment->type = $type;
$comment->text = $text;
$comment->created_by = $request->user()->first_name.' '.$request->user()->last_name;
$comment->save();
return response()->json(['success'=>'Success']);
}
HTML:
<form class="form-horizontal" method="POST" action="{{route ('storeComment')}}">
{{ csrf_field() }}
<input id="hidden-id" type="hidden" name="id" value="{{$id}}">
<div class="form-group">
<label class="col-md-4 control-label" for="commentSelect">Comment type</label>
<div class="col-md-6">
<select id="slect-comment-type" name="type" class="form-control">
<option value="Call">Call</option>
<option value="Mail">Mail</option>
</select>
</div>
</div>
<div class="form-group{{ $errors->has('comment') ? ' has-error' : '' }}">
<label for="comment" class="col-md-4 control-label">Comment</label>
<div class="col-md-6">
<textarea name="text" class="form-control" rows="5" id="comment"></textarea>
@if ($errors->has('comment'))
<span class="help-block">
<strong>{{ $errors->first('comment') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary btn-sm save-comment">Save</button>
</div>
</div>
</form>