I am creating a Ticket Reservation System and I want to check data availability from the Database. As usual, I used HTML form and when someone tries to insert data which is already in the database , I want to show them a message as "Data Already Have". And If data is unique , I want to insert into the database. But , when I click Submit button, nothing happens. ( Seat Number = Items )
In the console of the browser shows these errors -
POST http://localhost/FinalProject/public/seatprocess 500 (Internal
Server Error) XHR failed loading: POST
"http://localhost/FinalProject/public/seatprocess"
In Network tab -> Response shows like this -
{
"message": "Object of class Illuminate\\Database\\Query\\Builder could not be converted to string",
"exception": "ErrorException",
"file": "D:\\wamp64\\www\\FinalProject\\app\\Http\\Controllers\\SeatsController.php",
"line": 42,
"trace": [
{
"file": "D:\\wamp64\\www\\FinalProject\\app\\Http\\Controllers\\SeatsController.php",
"line": 42,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},
And this is continuesly going. May be my seatprocess function is wrong. But , I have no idea how to Fix it.
Form and Seat Structure Image
How can I Fix this ??
Here is my Seats.blade.php
<form class="form-horizontal" id="form1" method="POST" action="{{ route('seatsinsert') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="dt"> <br>
<h4> <span id="success_message" class="text-success"></span> </h4>
<div class="form-group row">
<label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
<div class="col-10">
<input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy" id="example-date-input">
</div>
</div>
<div class="form-group">
<label for="exampleSelect1">Select Time :</label>
<select name="st" class="form-control" id="exampleSelect1">
<option>10.30 am</option>
</select>
</div>
</div>
<h2 style="font-size:1.2em;font-family: Times New Roman;"> Choose seats by clicking below seats :</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="width:600px;text-align:center;overflow:auto"> <br>
<input type="submit" class="btn btn-primary" id="btnShowNew" value="Continue"> <br><br>
<span id="availability"></span>
<script type="text/javascript">
$(function () {
$('#btnShowNew').click(function (e) {
e.preventDefault();
var items = [];
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
items.push($(this).attr('title'));
});
console.log(items);
// $(location).attr('href', 'Seats');
$.ajax({
url:'{{ route('seatprocess') }}',
type:"POST",
data:{
_token: "{{ csrf_token() }}",
items: JSON.stringify(items),
date: $('input[name=date]').val(),
st: $('select[name=st]').val()},
success:function(data)
{
if(data !== '0')
{
$('#availability').html('<span class="text-danger">Seats not available</span>');
$('#btnShowNew').attr("disabled", true);
}
else
{
//$('#availability').html('<span class="text-success">Seats Available</span>');
$.ajax({
type: "post",
url: "{{ route('seatsinsert') }}",
data: {
_token: "{{ csrf_token() }}",
items: JSON.stringify(items),
date: $('input[name=date]').val(),
st: $('select[name=st]').val()},
success: function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html("Text");
}
});
$('#btnShowNew').attr("disabled", false);
}
}
});
}); //btnShowNew
}); //Final
</script>
</form>
Here is my SeatsController.php
public function seatsinsert(Request $request)
{
$date = $request->input('date');
$st = $request->input('st');
$items = $request->input('items');
$items = str_replace(['[', ']', '"'], '', $items);
$user = new Seats();
$user->date = $date;
$user->st = $st;
$user->item = $items;
$user->save();
}
public function seatprocess(Request $request)
{
//dd($request->all());
$items = $request->input('items');
$results = DB::table('seats')->where('item',$items);
echo $results;
}
}
Here are my Routes.
Route::post('seatsinsert',[
'uses'=> 'SeatsController#seatsinsert',
'as' => 'seatsinsert'
]);
Route::post('seatprocess',[
'uses'=> 'SeatsController#seatprocess',
'as' => 'seatprocess'
]);
You need to retrieve data in your response function with get like this before echo the $result variable.
This is the reason behind error in your console.
you have to change the line like this:
$results = DB::table('seats')->where('item',$items)->get();
Related
In my Laravel-5.8, I passed data from controller to view using JSON.
I am using Laravel-5.8 for a web application project.
I am trying to make my dropdown load value on a textbox on change.
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
$parentid = DB::table('appraisal_goal_types')->select('parent_id')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$weightedscore = DB::table('appraisal_goals')->select(DB::raw("SUM(weighted_score) as weighted_score"))->where('appraisal_identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->get();
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore
]);
}
I send the max_score and weighted_score as JSON.
route:
Route::get('get/findScore','Appraisal\AppraisalGoalsController#findScore')->name('get.scores.all'); view blade
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<input type="text" id="max_score" class="form-control" >
<input type="text" id="weighted_score" class="form-control" >
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
// console.log("price");
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore);
$('#weighted_score').val(data.weightedscore);
},
error:function(){
}
});
});
});
</script>
When I click on the dropdown on change the max_score is working perfectly, but the weighted_score is having error:
GET http://localhost:8888/peopleedge/get/findScore?id=2 500 (Internal Server Error).
Then I got this on my console:
and the textbox:
I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only 60 in the textbox.
How do I get this resolved?
Thank you.
$weightedscore is an object, so you should do the same for $weightedscore what you do for $maxscore: add the attribute and not the object to the response.
Change $weightedscore to $weightedscore->weighted_score in the return part.
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore->weighted_score
]);
You can output $weightedscore before returning it by using var_dump($weightedscore); or print_r($weightedscore); and then you will see that it is an object having an attribute called weighted_score as stated in your SELECT ... as() part of your SQL statement.
since it is array hence it will be
$('#max_score').val(data.maxscore['maxscore']);
$('#weighted_score').val(data.weightedscore['weightedscore'][0]);
['weightedscore']=keyname that you gave on the controller
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
// console.log("price");
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore['maxscore']);
$('#weighted_score').val(data.weightedscore['weightedscore'][0]);
},
error:function(){
}
});
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 error on my browser console: "PUT http://localhost:8000/post/2 500 (Internal Server Error)"
I use resource Controller and my route- Route::resource('post','PostController');
Here resource controller code for update post:
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->name = $request->name;
$post->content = $request->content;
$post->save();
return response()->json($post);
}
Here my view code:
<form class="form-horizontal" role="form">
<div class="form-group">
<input type="text" class="none" id="id">
<label class="control-label col-sm-2">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">content:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="content">
</div>
</div>
<div class="form-group">
<input type="submit" value="Edit" onclick="mainCatEdit();">
</div>
</form>
Ajax code:
function mainCatEdit() {
$.ajax({
url: '/maincategory/'+id,
type: 'PUT',
data: {
'_token': $('input[name=_token]').val(),
'id': $('#id').val(),
'name': $('#name').val(),
'content': $('#content').val()
},
success:function(data) {
console.log(data);
}
});
}
by the way i use meta token {{ csrf_token() }} on my file header.
but i get 500 internal server error on localhost.so someone help me.
You forgot to fill the data to your model, do this:
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->fill([
$post->name = $request->name;
$post->content = $request->content;
]);
$post->save();
return response()->json($post);
}
you are trying to get the value of a token you did not set, lets look at your code again without testing, just try this
set this at the top of your page under the meta tags
<meta name="csrf-token" content="{{ csrf_token() }}">
then your ajax should be
function mainCatEdit() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/maincategory/'+id,
type: 'PUT',
data: {
'id': $('#id').val(),
'name': $('#name').val(),
'content': $('#content').val()
},
success:function(data) {
console.log(data);
}
});
}
i hope this helps
I am trying to submit a simple form in UserFrosting and as a test only display the success message, with no data modification. I followed the guidance from Lesson 2 but I ran into the CSRF issue:
UserFrosting returns the following error:
Invalid or missing CSRF token.
What am I missing? Up until this point UserFrosting was very easy to digest :(
The form:
<form class="form-horizontal" role="form" name="requestDescription" action="{{site.uri.public}}/soap/requests/desc/edit/{{ keyname }}" method="post">
<div class="form-group">
<label for="input_group" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" id="input_name" class="form-control" name="lgname" placeholder="{{ name }}">
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Update</button>
</div>
</form>
with added script part to the bottom of the twig file:
<script>
$(document).ready(function() {
// Load the validator rules for this form
var validators = {{validators | raw}};
ufFormSubmit(
$("form[name='requestDescription']"),
validators,
$("#userfrosting-alerts"),
function(data, statusText, jqXHR) {
// Reload the page on success
window.location.reload(true);
}
);
});
</script>
Here are my two functions from the controller:
public function soapRequestDescriptionEditPage($keyname){
if (!$this->_app->user->checkAccess('uri_soap_requests')){
$this->_app->notFound();
}
$requestDetails = $this->soapRequestReadMeta($keyname);
$schema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/soap-request-description-edit.json");
$this->_app->jsValidator->setSchema($schema);
$this->_app->render('soap/soap-request-description-edit.twig', [
"name" => $requestDetails['name'],
"description" => $requestDetails['description'],
"keyname" => $keyname,
"validators" => $this->_app->jsValidator->rules()
]);
}
public function test(){
if (!$this->_app->user->checkAccess('uri_soap_requests')) {
$this->_app->notFound();
}
$post = $this->_app->request->post();
$ms = $this->_app->alerts;
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/soap-request-description-edit.json");
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
$ms->addMessageTranslated("success", "Everyone's title has been updated!", $post);
$rf->sanitize();
if (!$rf->validate()) {
$this->_app->halt(400);
}
$data = $rf->data();
}
Entries from the index.php file:
$app->post('/soap/requests/desc/edit/:request_id/?', function () use ($app) {
$controller = new UF\SoapController($app);
return $controller->test();
});
$app->get('/soap/requests/desc/edit/:request_id/?', function ($request_id) use ($app) {
$controller = new UF\SoapController($app);
return $controller->soapRequestDescriptionEditPage($request_id);
});
Finally, the schema:
{
"lgname" : {
"validators" : {
"length" : {
"min" : 1,
"max" : 150,
"message" : "The new title must be between 1 and 150 characters long."
}
},
"sanitizers" : {
"raw" : ""
}
}
}
As of UserFrosting 4, you should explicitly add the hidden CSRF input fields to your form. There is a partial template forms/csrf.html.twig that contains these fields, which you can insert using Twig's include tag:
<form class="form-horizontal" role="form" name="requestDescription" action="{{site.uri.public}}/soap/requests/desc/edit/{{ keyname }}" method="post">
{% include "forms/csrf.html.twig" %}
<div class="form-group">
<label for="input_group" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" id="input_name" class="form-control" name="lgname" placeholder="{{ name }}">
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Update</button>
</div>
</form>
For requests that are made without a form (for example, if it has been constructed purely in Javascript), you can grab the CSRF token name and value from the global site.csrf variable:
var userName = 'luke';
var fieldName = 'lgname';
var data = {
'value': fieldValue
};
data[site.csrf.keys.name] = site.csrf.name;
data[site.csrf.keys.value] = site.csrf.value;
var url = site.uri.public + '/api/users/u/' + userName + '/' + fieldName;
return $.ajax({
type: "PUT",
url: url,
data: data
}).done(function (response) {
window.location.reload();
});
It turned out that my code was fine. There were unrelated javascript errors on the page affecting UserFrosting form processing. Fixing these errors allowed UserFrosting to handle the form.
Note to self... make it a habit to look into the console for javascript errors :)
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");
}