MethodNotAllowedHttpException in RouteCollection.php line 251 while submiting form using ajax - php

I'm sending the html form using ajax to laravel controller but it showing the error that MethodNotAllowedHttpException in RouteCollection.php line 251.
here is my ajax codes.
<script type="text/javascript">
function Login(){
var data = $("#login-form").serialize();
$.ajaxSetup({
headers: {
'X-XSRF-Token': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
type:"POST",
url:"userAuth",
data:data,
success: function(response)
{
console.log(response);
},
error:function(response)
{
console.log(response);
}
});
}
</script>
controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function userAuth(Request $request)
{
$name = $request->username;
die($name);
}
}
?>
web.php codes
Route::post('/userAuth', 'LoginController#userAuth');
please let me know what I'm doing wrong thank and regards.

Request URL with the base URL & csrf token
<script type="text/javascript">
function Login(){
var data = $("#login-form").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
$.ajax({
type:"POST",
url: baseUrl+"/userAuth",
data:data,
success: function(response)
{
console.log(response);
},
error:function(response)
{
console.log(response);
}
});
}
</script>

in your api.php file put your route
Route::post('/userAuth', 'LoginController#userAuth');
your web.php file has a middleware for CSRF protection. You can disable it but not recommended

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

How to add a variable in ajax URL route

I am trying to concatenate a variable to my url link in ajax. The variable $news is the one that handles the notification id.
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var $news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients/", $news)}}', //returning an error undefined variable news
data: {newsID : $news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
In my web.php, it's route is inside a route group.
Route::group(['middleware' => 'auth:admin'], function () {
Route::prefix('admin')->group(function() {
Route::get('/recipients/{news}', 'Admin\NewsController#recipients');
});
});
So how can I make this work? By the way, my ajax is inside a blade.php file.
$news doesnt exist to blade because it executes on the time server is rendering the page. So your javascript hasn't been executed yet. To make this work, change you js code to this:
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients")}}' + '/' + news,
data: {newsID : news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});

Laravel 5.6 ajax post without form

I want to use ajax with selectize to load bdd results onchange.
I need to use post because I must send data to my url.
My function looks like this :
select_etages.load(function(callback) {
xhr && xhr.abort();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
data : { bat : value },
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
In my web.php I've got this :
Route::post('/lots/add/etages', ['as' => 'lots.add_post.select', 'uses' => 'Copro\LotController#select2']);
And my controller :
public function select(Request $request)
{
return "test";
}
But when I tried to use it, I've got an "419 unknown status". I can see that it's a post ajax and my data but I've got no error message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If I change to get it's working but not post.
Anyone know why I can't use post ??
Thank for your help.
Maybe you just rewrite the "select2" name end of the route to "select"?
I think you need to remove $.ajaxSetup function in callback function. Code might look like this.
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
select_etages.load(function(callback) {
xhr && xhr.abort();
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
});

Ajax Pagination Laravel 5.1

I'm trying to make a pagination with ajax and laravel 5, but I can not do the ajax works even with simple tests:
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "GET",
url: 'testeserver.php',
//url:"raphael.dev/testeserver.php",
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
In this example I try one have a return on json ,
<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>
but only with the error alert , in fact I'm trying with these following cases :
BlogController:
public function index(Request $request){
$artigos = Artigo::where('publicado_em', '<=', Carbon::now())
->orderBy('publicado_em', 'desc')
->paginate(config('blog.artigos_por_pagina'));
if ($request->ajax()) {
return Response::json(view('Blog.artigos', compact('artigos'))->render());
}
return view('Blog.index', compact('artigos'));
}
routes.php
post('/', 'BlogController#index');
get('/', 'BlogController#index');
get('/{slug}', 'BlogController#show');
jquery
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "POST",
url: 'page=' + page,
dataType: 'json',
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
Just found the solution, changed my jquery code to :
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
var url = '?page=' + page;
$.post( url, function(data) {
alert( "success"+data );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
And found a error in my BlogController :
in
if ($request->ajax()) {
return Response::json(view('Blog.artigos', compact('artigos'))->render());
}
the Facade Response was not declared, so just added
Use Request;
at the top,
but i still dont understand why the $ajax() dosent work, just the $get and $post
Laravel protects your application with CSRF tokens. When utilising Ajax you need to be sure to send across the CSRF token, otherwise Laravel will not process the request to protect your app.
$.ajax({
url: 'test',
type: "post",
data: {'_token': $('input[name=_token]').val()},
success: function (data) {
alert('the joys');
},
complete: function (data) {
}
});
Notice the $('input[name=_token]').val() - that will send your CSRF token. You will of course need to create a hidden input with the CSRF token in your view.
More information can be found here!

How to fix 500 error in AJAX and Laravel 5?

I've been stuck with a 500 (internal server error) for a long time and I don't know why. I need to pass these codes later.
Blade
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('#addChirp').submit(function() {
var msg = $('#message').val();
console.log(msg);
var dataString = "message="+msg;
console.log(dataString);
$.ajax({
type: "POST",
url: "post",
data: dataString,
success: function(data) {
console.log(data);
$('#showData').html(data);
},
error: function(data) {
alert("fail");
}
});
});
});
Routes
Route::post('post', function() {
if(Request::ajax()) {
return var_dump(Response::json(Request::all()));
}
});
Try calling Request and Response as a global facade following
Route::post('post', function() {
if(\Request::ajax()) {
return var_dump(\Response::json(\Request::all()));
}
});
If that does not work can you please update your question with full ajax response so problem can be narrowed down?
I think you havn't added any meta value in your head tag of html like
<meta name="csrf_token" content="{{ csrf_token() }}" />
If csrf tag exist than try modify your jax call.
X-CSRF-TOKEN': $('input[name="_token"]').value()
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls

Categories