Laravel AJAX NotFoundHttpException - php

I've been trying to use the AJAX in my laravel project but it always return an error,
NotFoundHttpException on RouteCollection.php", "line": 179
My route in web.php is
Route::post('/ajaxRequest','AjaxController#index');
The controller code is
class AjaxController extends Controller {
public function index(){
$msg = "Ajax test message";
return response()->json(array('msg'=> $msg), 200);
}
}
The Ajax call which I've used is
$.ajax({
type:'POST',
url:'{{url("/ajaxRequest")}}',
datatype:'json',
data: pass,
success:function(data){
$("#result").html(data.msg);
}
}).fail(function (jqXHR, textStatus, error) {
// Handle error here
$("#result").html(jqXHR.responseText);
});
and used the meta tag content for csrf_token
<meta name="csrf-token" content="{!! csrf_token() !!}">
And retrieved the value using
var pass={'_token': $('meta[name="csrf-token"]').attr('content')};
Please help me to resolve this error.

change route to this
Route::post('/ajaxRequest','AjaxController#index')->name('routeName');
and in ajax request make following changes:
$.ajax({
type:'POST',
url:'/ajaxRequest', //if in js file
url:'{{route("routeName")}}', //if in blade file
datatype:'json',
data: pass,
success:function(data){
$("#result").html(data.msg);
}
}).fail(function (jqXHR, textStatus, error) {
// Handle error here
$("#result").html(jqXHR.responseText);
});

Call route using route name
Route file
Route::post('/ajaxRequest','AjaxController#index')->name('ajaxRequest');
And your ajax request
$.ajax({
type:'POST',
url:'{{route("ajaxRequest")}}',
datatype:'json',
data: pass,
success:function(data){
$("#result").html(data.msg);
}
}).fail(function (jqXHR, textStatus, error) {
// Handle error here
$("#result").html(jqXHR.responseText);
});

Related

Update user attribute in Laravel calling a function on controller by pressing a button on blade view but without refresh page

I hava blade Laravel view where I have a button at the click of which I would like to update some user attributes. I have implemented in the controller a method to which pass the values ​​to be reported and saved on the user, but I do not want to update the page or change the URL. What is the correct method to do this?
Thank you.
web.php
Route::post('/updateUserPreference/{plan_compact_view}', [NutritionalPlanController::class, 'up
dateUserPreference'])->name('updateUserPreference');
blade view
#push('scripts')
<script type="text/javascript">
$(document).ready(function () {
$('#btn_view_type').click(function (e) {
//AJAX Call update user preference
$.ajax({
url: 'updateUserPreference',
method: 'post',
dataType: 'JSON',
success: function () {
console.log("done");
},error: function(xhr, ajaxOptions, thrownError){
console.log("error");
}
});
});
});
</script>
#endpush
Update 2
const planCompactView = true;
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/updateUserPreference/${planCompactView}',
method: 'post',
/* send the csrf-token and the input to the controller */
dataType: 'JSON',
data: {},
success: function () {
console.log("done");
//do something
},error: function(xhr, ajaxOptions, thrownError){
console.log(xhr.status+" ,"+" "+ajaxOptions+", "+thrownError);
}
});
Now the error message in console is: "200 , parsererror, SyntaxError: Unexpected end of JSON input"
The url in your ajax code snippet need to be changed to match the url defined in routes file
You also need to get the value for route parameter plan_compact_view and append it to the url in js snippet
#push('scripts')
<script type="text/javascript">
const planCompactView = 'get the value';
$(document).ready(function () {
$('#btn_view_type').click(function (e) {
//AJAX Call update user preference
$.ajax({
url: `/updateUserPreference/${planCompactView}`,
method: 'post',
dataType: 'JSON',
success: function () {
console.log("done");
},error: function(xhr, ajaxOptions, thrownError){
console.log("error");
}
});
});
});
</script>
#endpush

405: Method Not Found on POST request

I am recieving the 405: Method not Found error when trying to perform a POST request on my laravel application. I'm trying to make a forum to learn how to use php and Laravel.
I am trying to post the request from /forum/category/{category}/post, I perform (almost) identical requests from just /forum and it works perfectly, so I assume it's something to do with this.
This is where I'm trying to post the request from (returns post.blade.php):
Route::get('forum/category/{category}/post', 'ForumController#showThreadPostForm');
The request:
var $form = $('form');
$form.submit((e) => {
e.preventDefault();
$.ajax({
type: "POST",
url: 'postthread',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf"]').attr('content')},
data: {"test": "data"},
success: function(res) {
window.location.reload();
console.log(res);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("Error occured during AJAX request, error code: " + xhr.status);
},
});
});
The route:
Route::post('postthread', 'ForumController#postThread');
The controller method:
public function postThread(Request $request) {
//empty
}
I'm not sure if this information is enough.
Thanks.
I've used the same AJAX request on a different page /forum and it works, I'm not sure how to make it work on this page.
Try to add token to your data and add slash to your url.
also meta tag set to:
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajax({
type: "POST",
url: '/postthread',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf"]').attr('content')},
data: {"test": "data", "_token": $('meta[name="csrf"]').attr('content')},
success: function(res) {
window.location.reload();
console.log(res);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("Error occured during AJAX request, error code: " + xhr.status);
},
});

laravel 5.6 default login with ajax gives 422 Unprocessable Entity

I am using laravel 5.6 and I am trying to login with ajax. I have set all the things =>csrf ajax setup and also passing token, but I am still getting this when all credentials are right:
THis is my ajax code
$(document).ready(function () {
$('#sign-in-form').submit(function(ev) {
ev.preventDefault();
formData = $('#sign-in-form').serialize();
$.ajax({
url: '{{route('login')}}',
type: 'POST',
data: formData,
dataType: 'JSON',
beforeSend: function () {
// element.value='Processing...';
},
success: function (result, status, xhr) {
console.log(result);
},
error: function (xhr, status, error) {
alert(error);
}
});
})
});
There is nothing wrong with your codes. The message is the result of validations. To solve your issue you may need to enter at least 6 characters or more for your password and that should work.
Hope that helps.

Ajax calls return 419 error despite correct token in Laravel

I have a bunch of POST requests made with Ajax in my Laravel application.
A typical request looks like:
$.ajax({
url: '/path/to/method',
data: {'id': id},
type: 'POST',
datatype: 'JSON',
success: function (response) {
//handle data
},
error: function (response) {
//handle error
}
});
I have the CSRF token set and everything works fine most of the time:
jQuery(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
However, after a long hiatus (for example, computer asleep for a long time), all Ajax calls return a 419 error, as if the token wasn't set. After I reload the page everything is back to normal. This is on a local server.
How do I resolve this? Is there some way to "renew" the token before a call? Do I have to do the $.ajaxSetup bit before each call? It's not enough to do it once on page load?
This is my suggestion:
JS
//create a function to set header
function setHeader(data){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': data
}
});
}
//in first load of the page set the header
setHeader($('meta[name="csrf-token"]').attr('content'));
//create function to do the ajax request cos we need to recall it when token is expire
function runAjax(data){
$.ajax({
url: '/path/to/method',
data: {'id': id},
type: 'POST',
datatype: 'JSON',
success: function (response) {
//handle data
},
error: function (jqXHR, textStatus, errorThrown) {
if(jqXHR.status==419){//if you get 419 error which meantoken expired
refreshToken(function(){refresh the token
runAjax();//send ajax again
});
}
}
});
}
//token refresh function
function refreshToken(callback){
$.get('refresh-csrf').done(function(data){
setHeader(data);
callback(true);
});
}
//Optional: keep token updated every hour
setInterval(function(){
refreshToken(function(){
console.log("Token refreshed!");
});
}, 3600000); // 1 hour
Route
//route to get the token
Route::get('refresh-csrf', function(){
return csrf_token();
});
Hope this helps.

\HttpException while trying to query the database

I am using this ajax call
$.ajax({
url: "{{URL::to('/search/mask/byID')}}",
type: "post",
data: {value:value},
success: function (response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
And this is the controller
public function search(Request $request)
{
$maskID = 'Mask_' . $request->input('value');
$result = masks::where('MaskName', 'LIKE', $maskID)->get();
return $result;
}
And this is my route:
Route::post('/search/mask/byID', 'MaskSearchController#search');
I am getting HTTP 419 in Network tab once the ajax runs, and this is what I see at the response Route::post('/search/mask/byID', 'MaskSearchController#search');
The message is empty so I have NO Idea what could cause this :?
I also have
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
and the route is POST, so I don't send POST to GET.
Fixed, I forgot to add the meta
first check whether your routes are in routes/api.php only not in routes/web.php.

Categories