\HttpException while trying to query the database - php

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.

Related

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 AJAX NotFoundHttpException

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);
});

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.

Laravel Accessing JSON Post

I am struggling to post JSON data to Laravel. I have tried a number of ways to access the data in my controller, however, it returns []. I am not sure what I am doing wrong. I would greatly appreciate any help!
console.log(JSON.stringify(data)) output:
[{"ContactFirstName":"John","FamilyLastName":"Doe"}, {"ContactFirstName":"John","FamilyLastName":"Doe"}]
The AJAX Script:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: POST_URL,
type: 'POST',
dataType: "json",
data: data,
success: function (data) {
console.log(data);
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
The Laravel Controller:
$json = Request::json()->all();
return $json;
It returns []. I have tried Input::all() too and had no luck.
$JSON = file_get_contents('php://input');

Categories