When I try type something in input it is throwing error "405 Method not allowed". How can I fix this?
My route:
Route::get('/search' , [HomeController::class, 'searchPost'])->name('search-posts');
My blade:
<li><input id="search" name="search" autocomplete="off" class="form-control" placeholder=" " type="text" style="border-radius: 100rem;font-family:Arial, FontAwesome" >
My ajax:
$('body').on('keyup', '#search',function(){
var searchQuest = $(this).val();
$.ajax({
method:'POST',
url: '{{ route("search-posts") }}',
dataType: 'json',
data:{
searchQuest: searchQuest,
},
success: function(res){
console.log(res);
}
});
});
My controller:
public function searchPost(Request $request){
$search_users = User::where('username','like', '%' . $request->get('searchQuest') . '%')->get();
return json_encode($search_users);
}
In your Route:
Route::get...
In your AJAX:
$.ajax({
method:'POST',
...
The methods are differents, that's the error.
Related
I'm trying to create a personal messaging system in laravel, and apart of this system is being able to send messages in a form without refreshing the entire page.
I've been following some youtube tutorials, and this is the Ajax script I have so far.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
Instead of sending a POST request to the controller, it sends a GET request and just redirects.
This is my first time messing with Ajax/Javascript in general, so I don't know exactly why this isn't working.
Controller script:
public function sendM(Request $request, $id)
{
$validatedData = $request->validate([
'message' => 'required|string|max:255|min:4',
]);
$dm = Dm::find($id);
$mess = new Message;
$mess->Authid = Auth::user()->id;
$mess->Userid = $dm->Userid;
$mess->Dmid = $dm->id;
$mess->message = $request->input('message');
$dm->messages()->save($mess);
$dm->touch();
}
Route entry:
Route::post('/sendmessage/id{id}', 'SettingsController#sendM')->name('sendMessage')->middleware('verified');
Any help is very much appreciated! (Note: Sorry if it is something really obvious)
In the $.ajax call, you need to set the method to post instead of the type.
$.ajax({
method: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
As an aside, jquery is often considered to be on the way out. You may want to look into what some alternatives to jquery would look like, such as vue.js or react. Specific to the ajax aspect, Laravel has built in axios support.
Not sure if it solves your problem, but you must also add the csrf token to the headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
(if the token is in a meta tag of course)
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'POST', //Check your JQ version.
method: 'POST', //Check your JQ version.
contentType:"multipart/form-data; charset=utf-8",
//url: '{{ route("sendMessage", $dm->id) }}',
url: '{{ route("sendmessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
I am trying to make simple insert in laravel with AJAX but i keep getting 500 Internal server error. I believe i have included csrf_field properly. Any help is greatly appreciated!
web.php
Route::get( '/test', 'TestController#index');
Route::post('/korisnici', 'TestController#korisnici' )->name('korisnici');
test.blade.php
<script>
$(document).ready(function(){
var token = $('meta[name="csrf-token"]').attr('content');
$("#forma").click(function(){
var fname=$("#fname").val();
var email=$("#email").val();
$.ajax({
type:"POST",
url:"{{route('korisnici')}}",
data:"fname=" + fname + "&email=" + email + "&token=" + token,
success:function(data){
alert(data);
}
});
});
});
</script>
{{ csrf_field() }}
<input type="text" name="fname" id="fname" placeholder="first name"><br>
<input type="text" name="email" id="email" placeholder="Email"><br>
<input type="submit" id="forma">
TestController.php
public function korisnici(Request $request){
$fname=$request->input("fname");
$email=$request->input("email");
$this->validate($request,[
'email' => 'required|email',
'fname' => 'required'
]);
$data=array("ime"=>$fname,"email"=>$email);
DB::table("korisnik")->insert($data);
echo "ubaceno";
}
Pass your ajax call as below. you forget to mention e.preventDefault(); and pass your csrf_token in header.
$("#forma").click(function(e){
e.preventDefault();
var fname=$("#fname").val();
var email=$("#email").val();
$.ajax({
url : "{{route('korisnici')}}",
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data : {fname:fname,email:email},
success:function(data){
alert(data);
},
});
});
I'm trying to add an image to a post with Ajax / Laravel 5.4.
This is my HTML:
<form class="comments-form" action="/upload/comments/{{$post->id}}" method="post" data-id ="{{$post->id}}" enctype="multipart/form-data">
#csrf
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
Here is the Ajax code:
$('.add-comment').click(function(){
var comment_data = $('.comments-form').serialize();
var post_id = $('.comments-form').data('id');
var formData = new FormData('.comments-form');// i think here is problem
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,formData,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
This doesn't work – what am I doing wrong?
The FormData constructor takes a form not a string(you passes a css selector)
var formData = new FormData($('.comments-form').get(0));
If you use FormData in this way all fields in the form will be automatically added to the FormData object.
If there are items outside of the form fields that needs to be sent use the append method
formData.append('comment_data', $('.comments-form').data('id'));
When passing a FormData object to jQuery ajax you pass it alone and add processData and contentType set to false
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: formData,
contentType: false,
preocessData: false,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
If you want to store data using ajax.. you shouldn't need to put your action in your form component
<form class="comments-form" data-id ="{{$post->id}}">
{{ csrf_field() }}
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
</form>
I think if you want to submit your form, better to use jquery submit method
$('.add-comment').submit(function(){
var post_id = $('.comments-form').data('id');
var comment_data = new FormData($(".comments-form")[0]);
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,
dataType: 'json'
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
you can solve it as the following:
var formData = new FormData($("#FormId")[0]);
$.ajax({
url: '/upload/comments/' + post_id,
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: 'application/json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function (data, textStatus, jqXHR) {
console.log(data);
$('.all-comments').append(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error');
}
});
return false;
the formData variable contains all data of the form if you want to send the post id with the data sent you can put hidden field inside form called post id
like this
<input type="hidden" name="post_id" value="{{$post->id}}">
and then apply the above code
I have form to POST data to Controller and update database
The form in my orders.blade.php
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<select name="selectdb" required>
<option value="" disabled selected>Select Delivery Boy</option>
#foreach($delvery_boys as $delvery_boy)
<option name="selectdb" data-oid="{{$order->id}}" value="{{$delvery_boy->id}}">{{$delvery_boy->name}}</option>
#endforeach
</select>
<button type="submit" class="assigndb-btn btn-floating waves-effect waves-light">
<i class="material-icons">send</i>
</button>
</form>
I am doing an ajax POST request of form data to controller in my orders.blade.php
$(document).one("click", ".assigndb-btn", function () {
$('form').submit(function(event) {
event.preventDefault();
var order_id = $(this).find(":selected").data('oid');
var delivery_boy_id = $(this).find(":selected").val();
var delivery_boy_name = $(this).find(":selected").text();
$.ajax({
url: '{{ url('/manager/assign_orders') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And in my OrdersController.php i have the logic to updated the posted data
public function assignDeliveryBoy(Request $request)
{
$assign_delivery_boy = Order::where('id', $request->order_id)->update(['delivery_boy_id' => $request->delivery_boy_id]);
$data = [
'success' => true,
'message' => 'Order has been asigned'
];
return response()->json($data);
}
My Route is
Route::group(['prefix' => 'manager', 'middleware' => ['auth','roles'], 'roles' => 'manager'], function() {
Route::post('/assign_orders', 'OrdersController#assignDeliveryBoy')->name('assignOrder');
});
When i submit the form it suppose to hit the assign_order route and update the database
But in my console i am getting the html code of the page from where i submit the form basically it is executing GET instead of POST
As i checked in browser network whent the response is
Request URL:http://localhost:8000/manager/orders //but i am posting to http://localhost:8000/manager/assign_orders
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
i really don't understand what is wrong
thank you
Try this code.
$.ajax({
url: "{{ url('/manager/assign_orders') }}",
type: 'POST',
data:{
"order_id":order_id,
"delivery_boy_id":delivery_boy_id,
'_token':'{{ csrf_token() }}'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
Let me know if it works.
Try this:
$.ajax({
url: '{{ route('assignOrder') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
$.ajax({
url: '{{ route("assignOrder") }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id,'_token':'{{ csrf_token() }}'},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
I'm trying to submit a single value as following?
HTML:
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" name="frmanalyse" id="frmanalyse">
{{ csrf_field() }}
<label for="marginsource" style="float: left; width:150px; text-align:left;">Margin Source</label>
<input type="file" name="marginsource" id="marginsource" >
<br />
</form>
script:
<script type="text/javascript">
$( "#frmanalyse" ).submit(function(event) {
$.post( "marginanalyser", {username: "medo ampir"}, function( data ) {
alert(data);
});
event.preventDefault();
});
in laravel routes:
Route::post('marginanalyser',function(Request $request){
echo $request->input('username');
$file = $request->file('marginsource');
echo 'File Name: '.$file->getClientOriginalName();
});
nothing shows in the message at all.
Change your JavaScript to use FormData as you aren't submitting the file
$( "#frmanalyse" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('marginsource', $('#marginsource')[0].files[0]);
formData.append('username', "medo ampir");
$.ajax({
url : window.location.origin + "/marginanalyser",
type: "POST",
data : formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
});