Laravel route not found but data saved in DB - php

I am using laravel 5 POST route in an AJAX call, I have defined it as,
Route::post('user/save-draft', ['as' => 'user/save-draft', 'uses' => 'UserController#saveDraft']);
I am also using Route::resource for the same controller above this save-draft route as,
Route::resource('user', 'UserController', ['except' => 'index']);
I am posting a form using AJAX with loading icon, what I am having strange here is that, data get save in the database, but I receive 404 error in the console like,
jquery.js:9664 POST http://www.example.com/user/save-draft 404 (Not Found)
So strange, and loading icon never get disappear which I do in ajax.done function.
While, my AJAX call is something like that,
var postData = {};
postData['frmSaveDraft'] = $frmSaveDraft.serialize();
startAjaxLoading()
$.ajax({
url: "http://www.example.com/user/save-draft",
type: "POST",
data: postData,
success: function (data) {
alert('success')
stopAjaxLoading();
}
});
UPDATE: Sorry, I missed url in AJAX here in above question,
Any thoughts ?

In controller method, I was returning response as,
echo json_encode(array('response' => true)); exit;
which was causing this issue may be exit keyword.
I have returned the response like,
return Response::json(array('response' => true));
which works great.

Related

Laravel route not found in 8.54.0

I'm trying to get a simple ajax request working and all I'm getting is 404 errors. I've followed several tutorials to no avail.
the error I'm getting is: POST http://localhost/AjaxReq 404 (Not Found)
my ajax script on is my main.blade.php at the moment for testing
$.ajax({
url: '/AjaxReq',
type: 'POST',
dataType: 'html',
contentType:'application/json',
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data:
{
data1: 'ABC',
data2: 'DEF'
},
error: function() {alert('Error');},
success: function(response) {
$('#ajaxResponse').empty();
$('#ajaxResponse').append(response);
}
});
I have this in my web.php
use App\Http\Controllers\AjaxController;
and
Route::post('AjaxReq', [App\Http\Controllers\AjaxController::class, 'ajaxReq'])->name('ajaxReq');
my AjaxController.php is just this for now
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function ajaxReq(Request $request)
{
//
}
}
This is driving me mad, 12 YouTube videos and countless websites and posts on here and every time I get either this error or Controller not found.
Please help.
EDIT: changing to get and going to the page gives a 404, changing the route to your suggestion still 404 and route:list shows POST | AjaxReq | ajaxReq | App\Http\Controllers\AjaxController#ajaxReq | web –
EDIT 2:
ok so i can go to http://localhost/cms/public/AjaxReq with the route get to get and it will run what i put in the controller function but im still getting 404 on the ajax

axios delete route not supported laravel vuejs

I have a very strange issue with deleteing records. In my vuejs I call axios.delete to delete my record, which in turn calls my laravel route.
The record is getting deleted fine but an error message is displaying "message": "The DELETE method is not supported for this route. Supported methods: GET, HEAD.",
axios.delete('/member/event/' + this.data.module.slug);
My laravel route is as follows
Route::resource('event', 'EventController');
I am using laravel 6 to
It's high chance that delete url you try to send and route url are not the same, please check network and route:list, if not then you probably define your spa route at top, I mean the route except every params
The issue was nothing to do with the routes it was that I was not returning a json response after the delete which was causing the issue
Try this way-
routes routes/api.php
Route::apiResource('event','EventController');
In Controller Method
public function destroy(Event $event)
{
$event->delete();
return new EventResource($event);
}
In Your Components
axios.delete('/api/event/'+this.data.module.slug)
.then(response => {
console.log(response)
this.$snotify.success("Data Successfully Delete",'Success')
})
.catch(err => {
console.log(err)
})

DELETE and PUT does not recognize even after adjusting all required apache configurations

I have a Laravel app that I recently uploaded on the server.
From this Question I found that I should add these to end of htaccess file (after all laravel configurations) in public directory:
<Limit GET POST PUT DELETE>
Allow from all
</Limit>
But server can not recognize requests that sent via PUT or DELETE methods and shows this error :
501
Not Implemented
The requested method is not implemented by the server.
Apache version is 2.2.31 and operating system is linux.
What is problem and does remain something that I should be add?
Update:
This is a part of my routes related to issue:
Route::group(['prefix' => 'post'], function () {
Route::resource('/category', 'CategoryController');
});
In the other hand I used a $.delete user defined function like this to send DELETE requests:
$.delete = function (url, data, callback, type) {
if ($.isFunction(data)) {
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
dataType: type
});
}
And I used it to delete a category by it's ID:
$.delete('http://mysite.ir/post/category/20'+ , {}, function (res) {
// console.log(res);
}, 'json');
And destroy method that delete selected category:
public function destroy ($id, Request $request)
{
Category::destroy($id);
return ['success' => true, 'msg' => 'category removed.'];
}
It might be something you also need to change in your apache config file?

Laravel 5 making DELETE request by ajax - method not allowed

I'm trying to make a DELETE request within a Laravel app using ajax
I have a function to make the request - using the right verb - to a resource but keeps coming up method not allowed:
Here's my ajax request:
$.ajax({
type: 'DELETE',
url:'/user/58',
data: {
'_method': 'DELETE',
'id': id
},
dataType: 'json',
success: function (data) {
// do something with ajax data
if (data.result) {
return true;
}
return false;
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('error...', xhr);
return false;
//error logging
},
complete: function () {
//afer ajax call is completed
}
});
id is supplied within a function and for the test is 58.
Watching the network panel in Chrome I can see it starts with the expected url of user/58 but then quickly gets shortened to user
I know that to get the resource route to pick up the request it needs to be user/58 and the method DELETE so it will go to the destroy method and because of this it is being routed to the Index method which expects a GET request hence the method not allowed.
Why is my request url being changed?
What is the correct approach to make a DELETE request in Laravel?
Thanks
Edit:
Here's my route:
Route::group( [ 'middleware' => [ 'auth' , 'admin' ] ] , function ()
{
Route::resource( 'user' , 'UserController' );
} );
The csrf token is being taken care of in the headers - fairly certain this isn't the cause of problem as I do not get an invalid token exception
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Thanks
Two possible things that can happen here, I need to write this in a longer post than a comment so hopefully I got it right.
First thing that pops in my mind is an auth check that fails while doing the ajax request. At least I would redirect you back to the main resource if you wouldn't have enough rights.
However, my second guess is maybe even more likely. Have you thought of the X-CSRF-TOKEN that you need to send with an ajax request? See https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
From the docs:
In addition to checking for the CSRF token as a POST parameter, the Laravel VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a "meta" tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Once you have created the meta tag, you can instruct a library like jQuery to 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')
}
});

jQuery POST request always returns 404 not found with Laravel 4

Every time I try to make a POST request with jQuery I keep receiving back the 404 error.
This is the UserController.php:
class UserController extends BaseController {
public function signUp($username, $password, $email) {
$user = new User();
$user->setUsername($username);
$user->setPassword($password);
$user->setEmail($email);
return 'OK';
}
}
And this is the routes.php:
Route::get('/signup', function(){
return View::make('signup');
});
Route::post('/signup/{username}/{password}/{email}', 'UserController#signUp');
I always receive this error:
POST http://192.168.0.102/webname/public/signup 404 (Not Found)
Why is that? If I try to navigate to http://192.168.0.102/webname/public/signup the page is loaded and the signup form is shown.
You're are using a "GET" type route.
Let me explain.
If you want to use a route like /route/{something}/{different}
you have to manualy generate an URL matching that route.
URL::route('route', $something, $different)
Variable passed thought POST method are only available in the HTTP Headers.
So you can't call Route::post('/route/{variable}') by passing variable though POST method.
Only with Route::get().
To get your variable with POST use
Input::get('your_variable_name')
in your controller action.
Sorry for my bad english... A little bit tired, and I'm french too !
You are defining
Route::post('/signup/{username}/{password}/{email}', 'UserController#signUp');
But trying to access: /webname/public/signup.
That pattern does not exist for POST, but just for GET.
I had some troubles that were related to this discussion and in my opinion did not merit their own post: jQuery post requests kept getting handled by my Laravel get controller.
My routes:
Route::controller('/test','TestController');
In my view :
<script>
$(document).ready(function() {
jQuery.ajax({
type:'post',
url: '/test/x/',
success: function (response) {
alert(response);
}
});
});
</script>
My Controller:
public function getX() {
return 'Get';
}
public function postX() {
return 'Post';
}
On page load, I expected to see an alert reading "Post"... but instead I kept seeing "Get". Laravel was routing the post request to the get controller.
Solving this had to do with the trailing slash. Apparently, Laravel interpreted "/test/x/" as a GET route, but "/test/x" as a POST route. So the lesson is that Laravel routing can be subtle. Hope that helps clarify the discussion a bit.

Categories