I'm using resource controller , when i submit form through ajax , it is showing method not allowed exception.
View
{!! Form::open(array('route' => 'product.store','class' => 'form-horizontal','id' => 'productform','name' => 'productform','files' => true)) !!}
{!! csrf_field() !!}
<div class="form-group" style="padding-top: 20px">
<label for="productName" class="col-sm-3 control-label">Product name</label>
<div class="col-sm-9">
{!! Form::text('productName',null, array('id'=> 'productName','class'=>'form-control','placeholder'=>'Product name'))!!}
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
{!! Form::submit('Save', array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
{!! Form::close() !!}
AJAX
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: 'product/store',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
})
return false;
});
routes.php
Route::resource('product', 'ProductController');
What is the problem here...Any help is much appreciated.
in jquery
var BASEURL = $("#baseURL").val()
in html
<input type="hidden" id="baseURL" value="{{ url('') }}" >
when you try to store data in laravel your URL must be.
url: 'product',
try to go on your CMD and type:
php artisan route:list
and check the URI of product.store Name then that will be you url in your AJAX.
in AJAX
try to set url in AJAX to be route
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: '{{ route("product.store") }}',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
});
return false;
});
Related
Laravel Ajax validation worked [422 Status], but the page did not redirected if validation success and the data already inserted to DB
There was an error [422 Unprocessable Entity] but i solved as below in code.
i tried to solve that, it works and redirects successfully without enable ajax validation.
// Routes
Route::name('authorCreatePost')->get('post/create', 'AuthorController#createPost');
Route::name('_authorCreatePost')->post('post/create', 'AuthorController#_createPost');
// Controller
public function _createPost(Request $request)
{
$validator = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|min:20',
]);
if (!$validator)
{
return response()->json(['errors'=>$validator->errors()->all()]);
} else {
$post = new Post();
$post->title = $request['title'];
$post->content = $request['content'];
$post->user_id = Auth::id();
if ($post->save()) {
return redirect(route('authorCreatePost'))->with('success', 'Post Created Successfully');
}
}
}
// View
<form action="{{ route('_authorCreatePost') }}" method="POST" id="create-post-form">
#csrf
<div class="card">
<div class="card-header text-center text-uppercase h4 font-weight-normal bg-light">
{{ __('Create Post') }}
</div>
#if(Session::has('success'))
<div class="alert alert-success">{{ Session::get('success') }}</div>
#endif
<div class="alert alert-danger" style="display:none"></div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="title" class="require">{{ __('Title') }}</label>
<input id="title" name="title" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="content" class="require">{{ __('Content') }}</label>
<textarea id="content" name="content" class="form-control" rows="6"></textarea>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button id="submit" type="submit" class="btn btn-success btn-block">{{ __('Create') }}</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#create-post-form').submit(function(e){
validate_form(e);
});
function validate_form(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $("input[name='_token']").val(),
}
});
$.ajax({
url: "{{ route('_authorCreatePost') }}",
method: 'post',
data: {
_token: $("input[name='_token']").val(),
title: $('#title').val(),
content: $('#content').val(),
},
error: function(data){
if(data.status == 422) {
var errors = $.parseJSON(data.responseText).errors;
$('.alert-danger').empty();
$.each(errors, function(key, value){
$('.alert-danger').show();
$('.alert-danger').append('<p>'+value+'</p>');
});
}
},
});
}
});
</script>
[Validation works][1]
[Request and Response for 1][2]
[Here the data valid and inserted to DB][3]
[Request and Response for 3][4]
[1]: [https://i.stack.imgur.com/Shz0L.png][1]
[2]: [https://i.stack.imgur.com/FNbO7.png][1]
[3]: [https://i.stack.imgur.com/G6mSn.png][1]
[4]: [https://i.stack.imgur.com/QSr4s.png][1]
you can just return a success status from your controller
response()->json(['success' => 'success'], 200);
and then redirect in a success function in your ajax call
$.ajax({
url: "{{ route('_authorCreatePost') }}",
method: 'post',
data: {
//..
},
success: function(response){
window.location.href = "{{ route('authorCreatePost') }}";
},
error: function(data){
//...
},
});
or you can return the route to redirect from your controller
response()->json(['redirect' => route('authorCreatePost')], 200);
and then redirect to the route in the response on the ajax call success function
$.ajax({
url: "{{ route('_authorCreatePost') }}",
method: 'post',
data: {
//..
},
success: function(response){
window.location.href = response.redirect;
},
error: function(data){
//...
},
});
I have this form in a page:
<div class="card-block">
{!! Form::open(array( 'autocomplete' => 'off', 'id' => 'AddModel', 'url' => 'model/useradd', 'files' => true)) !!}
<div class="form-group">
<label for="picture">Picture</label>
#if( (new Jenssegers\Agent\Agent)->isMobile() )
{!! Form::file('image', ['id' => 'modelpic', 'accept' => 'image/*', 'capture' => 'camera']) !!}
#else
{!! Form::file('image', ['id' => 'modelpic']) !!}
#endif
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show preview of the image through JS */
<div class="form-group">
{!! Form::submit('Submit', array('id' => 'AddBtn', 'class' => 'btn btn-default' )) !!}
{!! Form::close() !!}
</div>
in my controller:
public function preview(Request $request)
{
dd($request->file('image'));
}
result of dumping = NULL
I don't understand what's the catch here. I have an identical form in another page that is working normally.
by validating request I get the error "image is required"
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png,gif|image|image_size:>=640'
]);
new info:
There must be a problem with the javascript because removing it the controller works normally:
this is the JS
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
solved, thanks #sagar
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
var postData = new FormData($("#AddModel")[0]);
$.ajax({
type:'POST',
url:form.prop('action'),
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
To upload image using ajax:
Do it like:
You can upload the file using ajax like this.
In your form tag use attribute enctype and form html will be like below:
<form enctype="multipart/form-data" id="modal_form_id" method="POST" >
<input type="file" name="documents">
</form>
Js code:
var postData = new FormData($("#modal_form_id")[0]);
$.ajax({
type:'POST',
url:'your-post-url',
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log("File Uploaded");
}
});
On your controller side you can do in the function like below to upload image.
if(Input::hasFile('documents')) {
$path = "directory where you wish to upload file";
$file_name= Input::file('documents');
$original_file_name = $file_name->getClientOriginalName();
$extension = $file_name->getClientOriginalExtension();
$fileWithoutExt = str_replace(".","",basename($original_file_name, $extension));
$updated_fileName = $fileWithoutExt."_".rand(0,99).".".$extension;
$uploaded = $file_name->move($path, $updated_fileName);
echo $updated_fileName;
}
More details :
File upload through a modal using Ajax
This code checks if request has a file if yes then names it and then moves the files to a folder in public dir.
if($request->hasFile('modelpic')) {
$file = Input::file('modelpic');
//get file extension
$name = 'image'.$file->getClientOriginalExtension();
//move file to public/images dir
$file->move(public_path().'/images/', $name);
}
Images are submitted with multiple part request due to size use (Multipart-form-data) in form tag.
Like this,
<div class="card-block">
{!! Form::open(array( 'autocomplete' => 'off', 'id' => 'AddModel', 'url' => 'model/useradd', 'files' => true,'enctype' => 'multipart/form-data')) !!}
<div class="form-group">
<label for="picture">Picture</label>
#if( (new Jenssegers\Agent\Agent)->isMobile() )
{!! Form::file('image', ['id' => 'modelpic', 'accept' => 'image/*', 'capture' => 'camera']) !!}
#else
{!! Form::file('image', ['id' => 'modelpic']) !!}
#endif
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show preview of the image through JS */
<div class="form-group">
{!! Form::submit('Submit', array('id' => 'AddBtn', 'class' => 'btn btn-default' )) !!}
{!! Form::close() !!}
</div>
when i try to upload my file with ajax, the $file is empty.
I tried with:
$file = Input::file('image');
$file= $request->file('image');
jQuery:
$(document).on('submit', '#update_form', function(e){
e.preventDefault(e);
$.ajax({
type: "POST",
url: '{{route('admin/users/update')}}',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('.error').fadeOut();
success(data);
load_data('{{route('admin/users/edit')}}', '{{ $user->id }}', '{{ $user->part }}');
},
error: function (data) {
$('.success').fadeOut();
errors(data);
}
})
});
Controller:
public function updateUser(Request $request){
//$file = Input::file('image');
$file= $request->file('image');
return \Response::json( $file );
}
Route:
Route::post('admin/users/update', ['as' => 'admin/users/update', 'uses' => 'admin\UserController#updateUser']);
Form:
{!! Form::model($user, ['id' => 'update_form', 'files' => true]) !!}
<div class="col-md-12">
<div class="form-group">
{{ Form::label(trans('User image')) }}
{!! Form::file('image', null,['class' => 'form-control', 'placeholder' => trans('Image')]) !!}
</div>
{{ Form::hidden('id') }}
{{ Form::hidden('part', app('request')->input('part')) }}
{!! Form::submit(trans('Save changes'), ['class' => 'pull-right btn btn-success submit', 'id' => 'submit' ]) !!}
</div>
{!! Form::close() !!}
Repsonse is empty or: {}
response image:
https://gyazo.com/04e431f16237dfada40c864df96ad412
Thank you!
param is your server method parameters
FormData fd =new FormData();
fd.append('param',$('input[type=file]').files[0]);
Laravel 6.x Ah finally nailed it down, for me the way its worked is first i have get the form by it's form id using jQuery then create a new FormData instance passing form through the constructor then if you need anything pass to server side as key value pair use append function.
<form id="form_id" enctype="multipart/form-data">
<div class="from-group">
<label for="title">App name:</label>
<input type="text" name="title" id ="title_id" class="form-control" placeholder="App name"><br>
</div>
<br>
<div class="form-group">
<input type="file" id="image" name="cover_image" autocomplete="off" class="form-control" />
</div>
<button type="button" onclick="WebApp.CategoryController.onClickAppSubmitButton()" class="btn btn-primary">Submit </button>
</form>
var form = $("#form_id")[0];
var formData = new FormData(form);
formData.append('parent_id','0');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: url_app_post,
method: "POST",
contentType: false,
processData: false,
data: formData,
success: function (result) {
var data_array = $.parseJSON(result);
if (data_array.status == "200") {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-success", data_array.message);
} else {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", data_array.message);
}
$(messageView).html(messageHtml);
},
error: function (jqXHR, exception) {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger",
WebApp.CategoryController.getjqXHRmessage(jqXHR, exception));
$(messageView).html(messageHtml);
}
})
function storeCategory(Request $request, $type){
try{
$fileNameToStore='no_image.jpg';
if($request->hasFile('cover_image')){
$fileNameWithExt = $request->file('cover_image')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('cover_image')->getClientOriginalExtension();
$fileNameToStore=$fileName.'_'.time().'.'.$extension;
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$cat = new Category();
$cat->title = $request->title;
$cat->parent_id = $request->parent_id;
$cat->cover_image=$fileNameToStore;
$cat->user_id=auth()->user()->id;
$cat->save();
return json_encode(array("message"=>"This ".$type." successfully added", "status" => "200"));
}catch(Exception $e){
return json_encode(array("message"=>$type." failed to insert: ".$e->getMessage(), "status" => "403"));
}
}
I want to add a comment system on my website using AJAX with Laravel to load new comments without refreshing whole page.
I always have this error :
Ajax Post 500 (Internal Server Error)
below is my code:
view page :
{!! Form::open(array('action' => array('PersonsController#newComment', $person->id))) !!}
<div class="form-group">
{!! Form::label('name', 'Nom ') !!}
{!! Form::text('name', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::label('mail', 'E-mail ') !!}
{!! Form::text('mail', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::label('comment', 'Contenu ') !!}
{!! Form::textarea('comment', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::submit('Publier', array('class'=>'send-btn')) !!}
</div>
{!! Form::close() !!}
route page :
Route::get('{id}/apropos','PersonsController#show');
Route::post('{id}/apropos','PersonsController#newComment');
Controller page :
public function newComment($id) {
if ($request::ajax()) {
$name = Input::get('name');
$mail = Input::get('mail');
$comment = Input::get('comment');
$Comments = new \App\Comment;
$Comments->Persons_id = $id;
$Comments->date = \Carbon\Carbon::now();
$Comments->name=$name;
$Comments->mail=$mail;
$Comments->comment=$comment;
$Comments->save();
$reponse =array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
} else {
return 'no';
}
}
Ajax page :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('.send-btn').click(function (e) {
e.preventDefault();
var name = $('#name').val();
var mail = $('#mail').val();
var comment = $('#comment').val();
$.ajax({
type: "POST",
url: '{{url("1/apropos")}}',
dataType: 'JSON',
data: {name: name, mail: mail, comment: comment},
success: function( data ) {
$("body").append("<div>"+data+"</div>");
}
});
});
});
I suppose that your ajax page is in the same page than the view (because you are using .send-btn).
It´s easier to use $.post() because you don´t need to configure so many parameters. https://api.jquery.com/jquery.post/
Do you have more information about the error: Ajax Post 500 (Internal Server Error). Don´t you have any message? Use error function on $.ajax:
error callback option is invoked, if the request fails. It receives
the jqXHR, a string indicating the error type, and an exception object
if applicable. Some built-in errors will provide a string as the
exception object: "abort", "timeout", "No Transport".
so you can add at your AJAX request something like:
error: function (xhr, textStatus, thrownError) {
console.log(xhr.status);
console.log(xhr.statusText);
console.log(textStatus);
console.log(thrownError);
}
I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:
POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)
What's wrong with my code? Is it the javascript or the controller?
EDIT: I'm getting this in laravel.log
exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
Route
Route::resource('articles', 'ArticlesController');
Controller
public function store(Requests\ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
$response = array(
'status' => 'success',
'msg' => 'Article has been posted.',
);
return \Response::json($response);
}
jQuery
$(document).ready(function() {
$('#frm').on('submit', function (e) {
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles/create',
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {
$("#ajaxResponse").append(data.msg);
console.log(data);
}
});
});
View
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<h1>Write a New Article</h1>
<hr>
{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
<p>
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}
</p>
<p>
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}
</p>
<p>
{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</p>
<p>
{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
</p>
{!! Form::close() !!}
<h3 id="ajaxResponse"></h3>
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
});
When you make a request via POST to a resource controller, it automatically calls store method:
Verb Path Action Route Name
----------------------------------
POST /articles store articles.store
So, you just need to change ajax url to:
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles',
When you need to send the session token, you can add a global meta-tag like this is you website:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, just add the token via ajax's headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you are using Form::open() function (LaravelCollective) it adds a hidden input with the token as value with the name _token. So, you can remove the meta-tag and edit your ajax's headers like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
That's what I got exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
You're hitting Laravel's CSRF protection.
http://laravel.com/docs/5.1/routing#csrf-protection
You need to pass the hidden _token field's value. This can be done automatically on all jQuery-initiated AJAX requests by doing this in your application's JS:
$.ajaxSetup({
headers: {
'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.
I like to share this code to help someone to need ajax post and get with laravel
<<<<<<<<
POST
<<<<
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login4')}}',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
alert(data);
console.log(data);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::post('login4', function()
{
return 'Success! POST Ajax in laravel 5';
})->name('login4');
------------------0----------------------
------------------0----------------------
<<<<
Get
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login2')}}',
type: "get",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
obj = JSON.stringify(data, null, " ");
var datito = JSON.parse(obj);
console.log(datito.response);
alert(datito.response);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::get('login2', 'WebController#login2')->name('login2');
-------------0----------------------
-------------0----------------------
<<<----<<Http\Controllers\WebController.php<<<<-----------<<<
public function login2(Request $datos) {
if ($datos->isMethod('get')) {
return response()->json(['response' => 'This is get method']);
}
return response()->json(['response' => 'This is post method']);
}
-------------0----------------------
-------------0----------------------
You can add your URLs to the VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification:
protected $except = [ "your url", "your url/abc" ];
Well if you are looking for the sure shot answer ,here it is :
This error particularly occurs if you are missing csrf_token() in your code
Here is what I did,
<h6>ITEMS ORDERED:CLICK HERE</h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Now With Ajax
<script type="text/javascript">
function getcart(val) {
var alpha=val;
var token=document.getElementById('token').value;
$.ajax({
type:'post',
url:'/private/getcart',
data:{'alpha':alpha,'_token': token},//this _token should be as it is
success:function (result) {
alert(result);
}
});
}
</script>
In my laravel controller
public function getcart(Request $req)
{
return response ("its");
}