500 Internal error - error TokenMismatchException - javascript

Seem to be having problems with a TokenMismatchException on my Javascript button that are approving a comment. I have copied the code from a similar button system and changed it to match the requirements of this system. I am reusing the Session:Token variable, not sure if thats the issue?
Error: TokenMismatchException in verifycsrftoken.php line 68
Here is my code, any ideas on why i'm getting the mismatch error?
HTML:
#if(Auth::user())
#if($approval)
<a class="approval approved " data-id="{{$comments->id}}"><i class="fa fa-thumbs-up"></i></a>
#else
<a class="approval not-approved " data-id="{{$comments->id}}"><i class="fa fa-thumbs-up"></i></a>
#endif
#else
<a class="not-approved" href="{{route('login')}}"><i class="fa fa-thumbs-up"></i></a>
#endif
Javascript:
var token = '{{ Session::token() }}';
var urlApproval = '{{ route('approvals') }}';
$('.approval').on('click', function(event){
event.preventDefault();
var buttonToChange = $(this);
var $this = $(this);
$.ajax({
method: 'POST',
url: urlApproval,
data: { comment_id: $(event.target).data("id")}, _token: token })
.done(function() {
if(buttonToChange.hasClass('approved')) {
buttonToChange.addClass('not-approved');
buttonToChange.removeClass('approved');
}else {
buttonToChange.addClass('approved');
buttonToChange.removeClass('not-approved');
}
});
});

When using ajax in laravel, and using POST method you always need to provide the csrf token, so what you need to do is:
In your HTML:
<meta name="csrf-token" content="{{ csrf_token() }}">
Before call Ajax:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Related

AJAX form submission in Django

I keep receiving 'Not Ajax' as a response during my form submission. I have to be missing something small but I cannot see it...
class VideoLikeView(View):
def post(self, request):
if request.is_ajax():
message = 'Ajax'
else:
message = 'Not Ajax'
return HttpResponse(message)
The AJAX code looks like this:
$(function () {
$("#like-form").submit(function (event) {
$.ajax({
type: "POST",
url: form.attr('action'),
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'pk': $(this).attr('value')},
success: function(response) {
alert('Video liked');
},
error: function(rs, e) {
alert(rs.responseText);
}
}
});
});
});
And my HTML:
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}">
<button type="submit">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
</form>
One question to add to this; how can I use an <input> in my form without using a <button>? I would like to use fontawesome icons but it seems I have to use a button to get the form to submit.
I found one answer on the internet that seems to work but I don't understand what the issue was. Seems like some type of serialization needed (?)... Anyways, here is what worked:
var frm = $('#like-form');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
return false;
});
Would love to hear from people why this works and not the previous..
try change your btn type button and add ID for event click :
since putting the submit button goes directly to view.py without going through AJAX
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}" id="id_pk">
<button type="button" id="id_btn">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
in your script
$("#id_btn").click(function() {
$.ajax({
url:window.location.origin + 'your url'
type: 'POST',
data: {'pk':$(#id_pk).val(), 'accion':'guardar'},
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
});
and your view.py
def post(self, request):
if 'guardar' in request.POST['accion']:
print("")

Ajax delete with laravel 500 internal error

Hi there I am new on coding so forgive me if I am asking too much, I have this problem here this is my HTML code on blade laravel:
<button type="button" id="removecollaborator" value="{{$bank_id}}" class="btn btn-flat btn-default btn-sm delete-colaboration-button"
title="#lang('buttons.remove_option')">
<i class="material-icons">delete</i>
</button>
and here I have my ajax js:
<script type="text/javascript">
$(document).on("click", "button[id=removecollaborator]", function (data) {
var result = confirm("Are you sure you want to delete this collaborator?");
if (result) {
var bankid = $(this).val();
$.ajax({
method: "POST",
url: "{{ url('/banks/delete-bank-collaborators') }}",
data: {
_token: "{{ csrf_token() }}",
bank_id: bankid
},
success: function () {
$("button[id=removecollaborator][value=" + bankid + "]").parent().parent().parent().parent().fadeOut('slow');
},
error: function () {
console.log("error");
}
});
}
});
</script>
And here I have the controller:
public function deleteCollaborator(){
if(request()->ajax()) {
$bank_id = request()->input('bank_id');
$bank_invites = BankInvite::select('id')->where('bank_id', $bank_id)->get()->toArray();
BankInvitedUser::whereIn('bank_invites_id', $bank_invites)->delete();
return response()->json(Lang::get('general.bank_deleted'));
}
It does not work I do not know why it returns Failed to load resource: the server responded with a status of 500 (Internal Server Error). so it is the success but I think in the controller I have the problem can someone help me, please..?
try replacing
deleteCollaborator(){
with
deleteCollaborator(Request $request){
also is your route a Route::post()?

Simple Ajax in Laravel

In a Laravel app, I need to update some data in the database after a button is clicked, without reloading the page, thus requiring ajax. No data needs to parsed, only a function in one of the controllers should be invoked, so it's the simplest kind of ajax request.
Based on this example, I set up the following, but nothing happens. No error, no response from the check alert('success!'), nothing.
QUESTION: why does nothing happen? Could it be that the Javascript is not recognized at al?
Head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Routes - web.php
Route::post('/notificationsSeen','NotificationController#seen');
Controller - NotificationController.php
public function seen() {
$userNotifications = Notification::where('user_id',Auth::id())
->where('status','new')
->update(array('status' => 'seen'));
return;
}
View
<button type="button" id="notifications"></button>
<script>
$("#notifications").on('click', function() {
$.ajax({
type:'POST',
url:'/notificationsSeen',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
alert('success!');
}
});
});
</script>
EDIT: WORKING SOLUTION
Change the contents of the box above labeled "View" to the following:
<button type="button" id="notifications"></button>
<script>
(function ($) {
$(document).ready(function() {
$('#notifications').on('click', function() {
$.ajax({
url: '/notificationsSeen',
type: 'POST',
data: { _token: '{{ csrf_token() }}' },
success:function(){alert('success!');},
error: function (){alert('error');},
});
});
});
}(jQuery));
</script>
In your AJAX request, data is not a string. It is a key value pair. So use
data: { _token: '{{ csrf_token() }}' }
You shouldn't pass the csrf token like this:
data:'_token = <?php echo csrf_token() ?>',
You have to store it in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then automatically add the token to all request headers:
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#notifications").on('click', function() {
$.ajax({
type:'POST',
url:'/notificationsSeen',
data: {status: 'seen'},
success:function(data){
alert('success!');
}
});
});
});
Controller:
public function seen() {
$userNotifications = Notification::where('user_id',Auth::id())
->where('status','new')
->update(array('status' => request()->input('status')));
return ['success' => true];
}

How to use ajax in laravel 5.3

I am new to Laravel and am using Laravel 5.3. I want to make a text field where it will automatically suggest some data and when I select a data it will add it to an array. I want to send that array to a controller for further use. For this the
view file is as follows:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var members = {!! json_encode($member) !!};
console.log(members);
var arr = [];
$("#tags").autocomplete({
source: members,
select: function (event, ui) {
arr.push(ui);
console.log(arr);
}
});
$("#submit").click(function(event){
$.ajax({
type: "POST",
url: '/storeresearch',
data: {selectedMembers: arr},
success: function( msg ) {
console.log(msg);
}
});
});
});
</script>
</head>
<body>
<form id="hu" action="/storeresearch" method="POST">
{!! csrf_field() !!}
<label>Research Author</label>
<input type="text" id="tags" name="researchsupervisor_1" value="">
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Add">
</form>
</body>
My Controller file is as follows:
public function store(Request $request){
if($request->ajax())
{
$mem = $request->all();
return response()->json($mem,200) ;
}
else{
return "not found";
}
And web.php is as followings:
Route::post('/storeresearch','ResearchController#store');
But it seems that there is no ajax call happening. In the controller it always enters the else section. What is the problem can anyone help?
Your code mostly looks good. But you are missing to send a csrf token with AJAX call as you are using POST request.
You can send csrf token with AJAX call in this way:
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
More info: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
When you hit the button, does it really fires an AJAX call? Please check that on network tab of browser.
I solved this problem by doing following
$.ajax({
type:'POST',
url:'your url',
data:{_token: "{{ csrf_token() }}"
},
success: function( msg ) {
}
});
Try some thing like this:
$.ajax({
url : '/login',
method : 'post',
data : {
login_username : userName,
password : password
},
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success : function(response){
}
});
Route:
Route::post('/login',[
'uses' => 'AdminServiceController#login'
]);
Controller method:
public function login()
{
$userName = INPUT::get('login_username');
$password = INPUT::get('password');
// your logic
}
What's your namespace declaration for Request ?
If it is use Illuminate\Http\Request; try use Request;

TokenMismatchException with javascript x-editable on Laravel 5.3

Before marking it as duplicated, i tried the other solutions found on the web, including SO, and none of them solved my issue.
I'm using x-editable plugin to store a new record using a store route.
When the form is submitted, i get a 500 with TokenMismatchException error.
I know about setting the csrf token thing, but i tried it in several ways, and nothing is working.
That's my javascript code:
$.fn.editable.defaults.params = function (params) {
params._token = window.Laravel.csrfToken;
return params;
};
$('.editable').each(function () {
$(this).editable();
});
The html
<head>
[...]
<meta name="csrf-token" content="{{ csrf_token() }}">
[...]
<script>
window.Laravel = <?php
echo json_encode([
'csrfToken' => csrf_token(),
]);
?>
</script>
[...]
</head>
<button id="note-asl-text"
data-type="textarea"
data-placeholder="Aggiungi Nota"
data-url="{{route('ricettanota.store')}}"
data-title="Inserisci una nuova nota"
data-highlight="false"
data-mode="inline"
data-send="always"
data-showbuttons="bottom"
class="editable"
>Aggiungi nota</button>
The Route
Route::resource('ricettanota', 'RicettaNotaController');
I already tried all possible combinations of the following:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
});
$('.editable').each(function () {
$(this).editable({
ajaxOptions: {contentType: 'application/json', dataType: 'json'},
params: function (params) {
params._token = window.Laravel.csrfToken;
return JSON.stringify(params);
}
});
});
note
$('meta[name="csrf-token"]').attr('content') and window.Laravel.csrfToken are the same
update
I found out that placing Route::resource('ricettanota', 'RicettaNotaController'); into the api routes file(api.php) causes the issue, while placing the routes into the web routes file (web.php) and using the code above works.
Why using the API i get token mismatch, is still a mystery.
Not sure if this is what you are looking for, but maybe you should not struggling in sending custom header with x-editable plugin, but sending custom parameters.
The following code works for me.
$(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.node').editable(
{
params: function(params) {
var data = {};
data['_csrf_token'] = $(this).data("csrf");
return data;
},
}
);
});
Set csrf in your a-tag or somewhere else you like.
<a href="#" ... data-csrf="xxxxxxx" /a>
Hope this helps.
try this in your ajaxSetup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I also faced same issue in Laravel 5.8. Following code worked for me.
$.fn.editable.defaults.ajaxOptions = {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
};
this is use code
$.ajax({
type: 'POST',
url: url,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType:'html',
data:data,
success:function(data){
}});
this Follow link
https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token

Categories