How to add a comment to a page using ajax - php

I am trying to allow the user to make a comment in an article but somehow, so that my page is not reloaded, I have to use ajax and I don't have much knowledge about it. This is how my comment section looks like:
<div class="usrcmmnt_list">
#foreach($comments as $comment)
<div class="usrcmmnt flex_box">
<div class="usrcmmnt_pic">
<img src="{{ $comment->user['profile_image'] }}">
</div>
<div class="usrcmmnt_area">
<p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
<div class="usrcmmnt_box">
<p class="usrcmmnt_text">{{$comment['content']}}</p>
<p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
</div>
</div>
</div>
#endforeach
</div>
<div class="comment_write">
<textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
<p class="usrcmmnt_text" id="textarea_warning"></p>
<span class="alert"></span>
<button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
</div>
</div>
In my script part, I have this one but it only copies the existing comments. This is just for my testing:
$('.comment_write button').on('click', function(e){
e.preventDefault();
var tmp = document.createElement('div');
$(tmp).load('myurl', function(data){
// usrcmmnt_list
var tmp2 = document.createElement('div');
$(tmp2).html(data);
var list = $(tmp2).find('.usrcmmnt_list');
$(".usrcmmnt_list").append(list);
});
});
How can I attain my goal using ajax?

There are multiple approaches for this, one of them:
you could move your comments loop (#foreach) into a partial
create an endpoint to save the user comment and return the new comments partial as html
update the DOM
1. Create a new partial \resources\views\partials\comments.blade.php and include it into your comments section:
#if ($comments)
#foreach($comments as $comment)
<div class="usrcmmnt flex_box">
<div class="usrcmmnt_pic">
<img src="{{ $comment->user['profile_image'] }}">
</div>
<div class="usrcmmnt_area">
<p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
<div class="usrcmmnt_box">
<p class="usrcmmnt_text">{{$comment['content']}}</p>
<p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
</div>
</div>
</div>
#endforeach
#else
No comments
#endif
2. Your comments section should look like this:
<div class="usrcmmnt_list">
<div id="comments-list">
#include('partials.comments')
</div>
<div class="comment_write">
<form method="post" action="{{ route('save.comment') }}" id="saveCommentForm">
<textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
<p class="usrcmmnt_text" id="textarea_warning"></p>
<span class="alert"></span>
<button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
</form>
</div>
</div>
3. Create your save comment method in CommentsController (which you will use to save the user comment via your ajax call):
public function save(Request $request)
{
/* we assume that your ajax save route is named comment.save */
/* you might need the postId if you save the comments for a post */
$comment = $request->input('comment');
$user = auth()->user();
$comment = Comment::create([
'user_id'=> $user->id,
'content'=> $comment
]);
$comments = Comment::with('user')->all();
return view('comments.blade');
}
4. Your ajax call:
$(document).ready(function(){
$('#saveCommentForm').on('submit', function(event) {
event.preventDefault(); // prevent the form from submiting
var $form = $(this),
url = $form.attr('action');
$.ajax({
url: url,
method: 'POST',
data: $form.serialize(),
success: function(response) {
$('#comments-list').html(response); //update the dom
},
error: function() {
alert('An error occurred. Please try again later.');
}
});
});
});
I hope this will help you get started.

You must try something like this.
$(document).on('click', '#saveComment', function(){
if($('#comment').val()==''){
alert('Please write a Comment First!');
}
else{
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: '<your url goes here>',
data: {"comment": comment},
success: function(){
// update comment listing.
},
});
}
});
However here is the complete tutorial you can follow. https://www.sourcecodester.com/tutorials/php/11819/laravel-comment-post-using-ajax.html

Related

How to submit a blade.php form with AJAX

How should I handle the csrf_field() function when doing this with AJAX?
here is a link to the project repo.
Here is a link to the article which helped me write the code.
I'm pretty sure I don't have to make too many changes to the code to handle the forms with AJAX instead of regular blade.php form submissions, but I'm unsure of the implementation
<form id="add_item" method="POST" action="/item">
<div class="form-group">
<textarea name="item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" >Add Item</button>
</div>
{{ csrf_field() }}
</form>
you can also put csrf-token in header file like this...
<meta name="csrf-token" content="{{ csrf_token() }}">
then give one unique id to submit button... then after in JavaScript detect that click event. then after call ajax on click event of submit button
$.ajax({
type: "POST",
// url: "{{ route('admin.users')}}" + id,
// url : '/admin/users/',
url: "{{url('admin/users/')}}", // you can pass url using url() OR as simple url OR Route name also
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //get the Csrf token from header
},
data: { id: id, }, //pass here all data which you want to pass to controller
success: function (data) {
console.log(data);
}
});
get the csrf value using
var token = $('input[name="csrfToken"]').attr('value');
and append it to the header
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
you can read more about it here https://stackoverflow.com/a/51964045/9890762
SOLVED.
I had to remove the 'type' attribute from the form as ajax is being used instead,
and ensure the ajax functions are at /public/js/file.js
Then, to make the changes available to the folder resources
npm run dev
<form id="add_item_form" action="/item">
<div class="form-group">
<textarea id="add_item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button id="ajaxSubmit_add">Add Item</button>
</div>
</form>

Laravel 5: Request data is null when using an Ajax Post Request

I have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?
My code at the moment as we speak:
showuser.blade.php
<div class="comments">
#if(count($user->cars))
<h1>Auto in reparatie</h1>
<hr>
#foreach($user->cars as $car)
<!-- Form to show each car and edit / delete the cars -->
<!--<form action="{{ action('CarController#edit', [$user->id, $car->id]) }}" method="POST">-->
<form>
<div class="form-group">
<label for="brand">Merk:</label><br>
<select name="brand">
#foreach($brands as $brand)
<option value="{{$brand->id}}"{{ $brand->id == $car->brand_id ? ' selected="selected"' : '' }}>{{$brand->brandname}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="year">Bouwjaar:</label><br>
<input type="text" value="{{$car->year}}" name="year">
</div>
<div class="form-group">
<label for="licentsplate">Kenteken:</label><br>
<input type="text" value="{{$car->licensplate}}" name="licenseplate">
</div>
<div style="float: left; width: 80px">
<input type="submit" class="btn btn-primary" value="Edit" id="{{$car->id}}" name="editcar" />
</div>
</form>
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
#endforeach
#endif
</div>
Script
<script type="text/javascript">
$( document ).ready(function() {
$('[name="editcar"]').click(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
})
});
});
</script>
Routes
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
CarController.php
// Function to edit a car by ID
public function edit($userId, $carId)
{
$car = Car::where('id', $carId)->where('user_id', $userId)->first();
$car->brand_id = request('brand');
dd(request('year'));
$car->year = request('year');
$car->licensplate = ('licenseplate');
$car->save();
}
If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.
EDIT:
If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.
Thx for reading!
You aren't posting any data in the AJAX request. Pass the form values through in an object.
var form = $(this).find('form');
var licenseval = form.find('input[name=licenseplate]').val();
var yearval = form.find('input[name=year]').val();
var brandval = form.find('select[name=brand]').find(":selected").val();
$.ajax({
type: "POST",
data: {licenseplate: licenseval, year: yearval, brand: brandval}
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
});
Change following lines:
public function edit($userId, $carId)
to
public function edit(Request $request, $userId, $carId)
and use
use Illuminate\Http\Request;
after that you can get $userId, $carId to use inside the controller function.
As per your ajax call you are only calling the route
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
but you are not passing any other value. Your application is working as expected.
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
//data: dataObject, ----->Missing Data which you want to pass (brand, year, licenceplate)
success:function(data){
//...
}
})
You are iterating through multiple $cars you need to get current car's data and pass to ajax call.

Jquery pass value to radio button

I used jquery ajax code to run search function.
here's my ajax so far :
$('button[type="search"]').click(function(e) {
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'});
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
});
and the data being returned like this on my network (inpect element) :
car_id:5
driver_id:1
end_time:"2016-11-16 18:00:00"
plate_no:"DFE82846J"
start_time:"2016-11-16 08:00:00"
working_date:"2016-11-16 00:00:00"
here's the form blade code so far :
<div class="row top">
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label class="control-label">Driver Name:</label>
{!! Form::select('driver_id', $driver, null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label>Fine Date:</label>
{!! Form::text('fine_date', null, array('id' => 'datetimepicker', 'class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group filter-btn">
<button class='btn btn-info' type='search'>Search</button>
</div>
</div>
</div>
<div class="row mid ">
<div class="col-xs-4 col-sm-4 col-md-4">
<div id="search-result"></div>
</div>
</div>
the issue is I can't save. it throws error car_id' cannot be null'.
how do i pass car_id into my radio, so once i clicked on radio button it save car_id by plate_no
im using laravel 5.3
It's unclear to me where you have PlateEle, StartEle and EndEle defined. Are those global vars defined elsewhere in your javascript?
Either way, as I understand it, car_id is being returned by the ajax POST, so it's in the data var returned to your success function?
If you want to set the value in the radio element you're creating dynamically I think it would be this:
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
Here is an example I mocked up. I am creating a data object like what I believe you're saying is being returned. When I load this page I get a radio input created. Does this work for you?
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result= $('#search-result');
//mocking up what I assume your data object looks like
var data = {};
data.car_id=5;
data.driver_id=1;
data.end_time="2016-11-16 18:00:00";
data.plate_no="DFE82846J";
data.start_time="2016-11-16 08:00:00";
data.working_date="2016-11-16 00:00:00";
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
console.log(PlateEle);
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
$('#search-result').append(PlateEle, StartEle, EndEle);
});
</script>
</head>
<body>
<div id="search-result"></div>
</body>
</html>
To save the value on your input radio this could should make the trick:
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input type="radio" name="rad" val="'+data.car_id+'">'+data.car_id+'</input>');
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
Well, adding or changing value of radio buttons is simple. For your ID in database you could also use some data-* attribute on your radio button. But remember, data-* on your form elements will not be sent to the server, if the form is submitted in browser. For more details see my working code example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Radio Button</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
var $rdBtn = null;
var $txtReader = null;
var $txtRdBtnValueReader = null;
function doReady() {
$rdBtn = $("#myRdBtn");
$txtReader = $("#txtDataReader");
$txtRdBtnValueReader = $("#txtRdBtnValueReader");
$("#btnSetValue")
.click(function () {
// note the jQuery .val("some text") issue at this point. You will need .attr("value") for setting
// .val() is just helpful for reading the current value!
$rdBtn.attr("value", "my new value");
$txtRdBtnValueReader.attr("value", $rdBtn.val());
});
$("#btnSetDataValue")
.click(function () {
$rdBtn.data("mykey", "myval");
$txtReader.attr("value", $rdBtn.data("mykey"));
});
}
$(document).ready(doReady);
</script>
</head>
<body>
<button type="button" id="btnSetValue">set Value</button>
<button type="button" id="btnSetDataValue">set data-* value</button>
<div id="myRadioButtonWrapper">
<label for="myRdBtn">your value choice</label>
<input type="radio" id="myRdBtn" name="myRdBtn" value="to be replaced" />
<br />
<label for="txtRdBtnValueReader">radio value</label>
<input type="text" id="txtRdBtnValueReader" name="txtRdBtnValueReader" readonly />
<br />
<label for="txtDataReader">data-mykey value</label>
<input type="text" id="txtDataReader" name="txtDataReader" readonly />
</div>
</body>
</html>
It is also a common way if you need more data assigned to an input field to serialize its value as json. So, that you could have a whole object sent to the server. It's easy to parse again in PHP. Maybe this could help you, too. Good luck!

Page is going blank after json response in laravel

Edit: Here's a little video of my problem: The video
I'm working on my socket based chat app in laravel 5.2. I was basing on this tutorial. Here's what I do and what's the problem:
I run my mysql server
I run redis-server
I run 'node server.js'
I run 'sudo php artisan serve --port=80'
I enter my site in the browser
I log in
I'm redirected to chat page
I enter an massage and send it
Page goes all white with '[]' being the only content
After running chat in two browsers and sending an message in one of them, the message appears properly on the other one. I'm running OS X ElCaptain.
Here's my routes file:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::auth();
// Route::get('/chat', 'ChatController#index');
Route::get('/home', 'HomeController#index');
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/chat', 'ChatController#index');
});
Route::post('sendmessage', 'ChatController#sendMessage');
Here's my ChatController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Request;
use LRedis;
class ChatController extends Controller {
public function __construct() {
// $this->middleware('guest');
}
public function index() {
return view('chat.index');
}
public function sendMessage() {
$redis = LRedis::connection();
$data = [
'message' => Request::input('message'),
'user' => Request::input('user')
];
$redis->publish('message', json_encode($data));
/*
Content-Type is set to text/html because otherwise there was an error
in JavaScript console.log:
Resource interpreted as script but transferred with MIME type application/json.
*/
return response()->json([])->header('Content-Type', 'text/html');
}
}
Here's my view:
#extends('layouts.app')
#section('title', 'CityChat')
#section('styles')
<link rel="stylesheet" href="{{ URL::asset('assets/css/chat/index.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
#endsection
#section('scripts')
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="{{ URL::asset('assets/js/chat/index.js') }}"></script>
#endsection
#section('content')
<div id="chat" class="ui container">
<div class="ui grid">
<div class="four wide column">
<div id="users" class="ui segment">
<div class="ui list">
(div.item>strong{username$})*50
</div>
</div>
</div>
<div class="twelve wide column">
<div id="messages" class="ui top attached segment">
</div>
<div class="ui bottom attached segment">
<form action="sendmessage" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
<input type="hidden" name="user" value="{{ Auth::user()->name }}" >
<div class="ui fluid transparent input">
<input class="msg" type="text" name="message" placeholder="Tu wpisz swoją wiadomość">
<button type="button" class="ui button send">Wyślij</button>
{{-- <input type="button" class="send-msg" name="send" value="Send"> --}}
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Of course jquery is implemented in layouts.app before the index.js, which is:
var socket = io.connect('http://localhost:8890');
socket.on('message', function(data) {
data = jQuery.parseJSON(data);
console.log(data.user);
$("#messages").append("<p><strong>" + data.user + ":</strong> " + data.message + "</p>");
});
$(".send").on('submit', function(e) {
e.preventDefault();
var token = $("input[name ='_token']").val();
var user = $("input[name ='user']").val();
var msg = $(".msg").val();
if (msg != '') {
$.ajax({
type: "POST",
url: '{!! URL::to("sendmessage") !!}',
dataType: "json",
data: {
'_token': token,
'message': msg,
'user': user
},
success: function(data) {
console.log(data);
console.log();
$(".msg").val('');
}
});
} else {
alert("Please Add Message.");
}
})
And here's the server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890);
io.on('connection', function(socket) {
console.log("client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, data) {
console.log("mew message add in queue " + data['message'] + " channel");
socket.emit(channel, data);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
I don't know what else could be helpful. I hope you will help me guys :)

Laravel 5: Ajax Post 500 (Internal Server Error)

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\Htt‌​p\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");
}

Categories