updation issue during with ajax method - laravel

i am trying to update my record with ajax and i don't know here i am doing wrong the code with my ajax:
$(document).ready(function(){
$('.edit_tag_button').click(function(){
var id = $(this).parent().find('.tag_id').val();
var formData = {
'tag_type' : $('#tag_type').val(),
'quantity' : $('#quantity').val(),
'number' : $('#number').val(),
'active' : $('#active').val(),
'issued' : $('#issued').val(),
};
$.ajax({
url: "{{url('')}}/update/tagslist/"+id,// Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
success: function(data) {
swal("Success!", "Great Job!! Your data has been updated","success");
location.reload();
},
error: function () {
swal("Error", "Look like We got some problem. Can you please refresh the page and try again" , "error");
}
});
});
});
and my controller code is:
public function updateTags(Request $request,$id)
{
$plan = Tags::where('id',$id);
$plan->update($request->all());
}
it says your values updated successfully but it does update my values any help plz

In Laravel POST method required CSRF protection.
Make sure to add meta with csrf token content
<meta name="_token" content="{{ csrf_token() }}">
And share it to ajax setup.
$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}});

Related

Form Post Request with Authentication Middleware throws error 419 Page Expired in Laravel 8

I have a form to create a card, this form is public, when a person fills out the form and wants to publish their card, they are asked to log in or if they are a new user to register.
I suppose that when the login is requested, the token that was immersed in the form expires and throws the 419 error.
How can I login and update the token to avoid error 419?
I am not an expert in Laravel so any suggestions would be appreciated.
reference diagram
here a part of the code that I have implemented
Login via AJAX
$(function () {
$('#login-form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var url = form.prop('action');
let data = form.serializeArray();
console.log(data);
$.ajax({
type: "post",
headers: {
Accept: "application/json",
},
url: url,
data: form.serializeArray(),
success: function(json) {
console.log('OK')
},
error: function(json) {
console.log('NOK')
alert(json);
},
});
});
});
Controller
public function __construct()
{
$this->middleware('create.card.newuser')->only('store');
$this->middleware('auth')->except(['create', 'store']);
}
Middleware "CreateCardIfNewUser"
public function handle(Request $request, Closure $next)
{
if (! Auth::user() )
{
return redirect()->route('digital_card.create')->with('openModalLogin', true)
->withInput($request->all());
}
return $next($request);
}
View 'layouts.app'
#if(session()->has('openModalLogin'))
<script>
$('#login-modal').modal({
show: true
});
</script>
#endif
Pass the csrf_token to the data:
…
data : {
_token: "{{ csrf_token() }}"
}
your error is due to the absence of csrf token. this solution is not only valid on this problem. each time you will have this problem of 419 then you must immediately think of the csrf token
data: {
_token: "{{ csrf_token() }}"
}
you must always add a csrf token to each submission otherwise you will always get this error
data: {
_token: "{{ csrf_token() }}"
},

Post data on database with ajax laravel

I have a counter in Ajax and I would like to save the value of the counter in a database so that the value of the counter continues to grow even when the user disconnects or refreshes the page. I use the laravel framework. how to do it, please?
Add the csrf_token() to somewhere on the blade view:
<input type='hidden' name='_token' value='{{ csrf_token() }}' id="csrf">
Add this route to your routes/web.php file:
Route::post('add-to-counter', 'YourController#add');
Your php script:
public function add()
{
// retrieve de counter value from the database:
$i = DB::table(...)->select(...)->get();
$i = ++$i;
// and save it to the database
return response()->json([
'data' => $i
]);
}
Then, create a ajax request:
let _token = $("#csrf").val();
$.ajax({
url: 'add-to-counter',
method: 'post',
data: {
'_token': _token,
}
success: function(response){
// What happens if the ajax request finishes successfully
alert("The current counter value is: "+response.data);
}
});

csrf validation in yii2 not working

I have enabled csrf validation as true in my controller.But after few minutes, while submitting the form,csrf token got expired and got bad request message,eventhough I am passing csrf token through ajax.Please provide me a solution to get over this issue.
Below is my sample code
Controller
public function beforeAction($action)
{
$this->enableCsrfValidation = true;
return parent::beforeAction($action);
}
JS page
var csrfToken = $('meta[name="csrf-token"]').attr("content");
Ajax call
var values = {
'id' : id,
'cpcode' : cpcode,
'_csrf' : csrfToken
};
$.ajax({
type : 'POST', //Method type
url : baseurl +'/site/test',
data : values,
dataType : 'json',
success : function(data)
{
}
}
);
main.php
<head> <?= Html::csrfMetaTags() ?></head>
Try add header like this:
$.ajax({
...
headers: {'X-CSRF-Token':"U05vc3J6YmVmPgAaFh8gAiMvPBQTETMrBjc8JRA4GywBBwMGAzA7Og=="},
...
}
Shouldn't it be:
var values = {
'id': id,
'cpcode': cpcode,
yii.getCsrfParam(): yii.getCsrfToken()
};

Laravel ajax 500 (Internal Server Error)

I am trying to do an ajax call in laravel. The ajax call logs my data how I want it, but keeps giving me the 500 error. I've read that you need to set the _token in the data field. But that doesn't work for me. So, I can log all the data, but ones I want to push it to the DB I keep getting this error.
Here's my code.
Script.js
$('.likeBtn').click(function(e){
e.preventDefault();
var userid=$(this).siblings('input[name=userID]');
console.log(userid[0].value);
var useridarticle=$(this).siblings('input[name=userIdFk]');
console.log(useridarticle[0].value);
var articleid=$(this).siblings('input[name=articleId]');
console.log(articleid[0].value);
var token=$(this).siblings('input[name=_token]');
console.log(token[0].value);
$.ajax({
url:"articles" ,
type: "post",
data: {'user_id':userid[0].value,
'article_id':articleid[0].value,
'user_id_fk':useridarticle[0].value,
'_token': token[0].value},
success: function(data){
console.log(data);
}
});
});
Controller.
if(Request::ajax()) {
$data = Input::all();
print_r($data);
}
My tokens are set in the header of my master.blade
<meta name="_token" content="{!! csrf_token() !!}"/>
And at the end of my master.blade
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
What am I not seeing? FYI, You might ask why I need does variables. I need them because I generate the same form in a foreach. This works fine for me, i get the data that I want so.

joomla token is not getting recognized by controllers method

I'm trying to set up a token on ajax post but is not getting recognized by the controllers method. The javascrip looks as it follows
jQuery(document).ready(function() {
jQuery('#source').change(function() {
jQuery('#fileupload').addClass('fileupload-processing');
var data = jQuery('#source option:selected').val();
jQuery.post('index.php', {
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'token':'<?php echo JUtility::getToken()?>',
'app': data,
'dataType': 'html',
}, function(result) {
jQuery('td.add_column').html(result);
jQuery('button#parse.btn').show();
//edit the result here
return;
});
});
the token is getting generated and posted
in the controller I check the existance of toke but throws me Invalid Token
controller check toke
JRequest::checkToken('request') or jexit( 'Invalid Token' );
You're almost there, it's just a little mixed up. The Joomla! Form Token is generated and submitted as a input name with a value of 1. So, the token looks like this in your form:
<input type="hidden" name="1LKJFO39UKSDJF1LO8UFANL34R" value="1" />
With that in mind, when submitting via AJAX, you need to set the parameter name to your token name, with a value of 1. I accomplish something similar by just using the jQuery('selector').serialize() method:
Joomla.autoSave = function () {
jQuery.ajax({
url: "index.php?option=com_gazebos&task=product.apply&tmpl=component",
type: "POST",
data: jQuery("#product-form").serialize(),
success: function (data) {
console.log("autosaved");
}
});
};
Doing this pulls in all the form data (including the form token from the hidden input) and formats it as a query string, then sends it with the request. However, it seems to me that you might not want to do that and you are really only wanting to submit a single bit of data, not the whole form. So, let's rework your code a little bit to get the desired effect:
/**
* First, let's alias $ to jQuery inside this block,
* then setup a var to hold our select list dom object.
*/
jQuery(document).ready(function ($) {
var sourceSelect = $('#source');
sourceSelect.change(function () {
$('#fileupload').addClass('fileupload-processing');
/**
* Use the token as a parameter name and 1 as the value,
* and move the dataType param to after the success method.
*/
$.post('index.php',
{
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'app': sourceSelect.val(),
'<?php echo JSession::getFormToken()?>': 1
},
function(result) {
$('td.add_column').html(result);
$('button#parse.btn').show();
//edit the result here
return;
},
'html'
);
});
});
Finally, this code is assuming you have this js code either in your view.html.php or in your views/parser/tmpl/default.php. If you have it in a separate .js file, then your php code won't execute and give you the token.
In your ajax call method use url as :
$.ajax({
url: '/index.php?option=com_itemreview&task=item.userReviewVote&<?php echo JSession::getFormToken(); ?>=1',
type: 'post',
data: {'data': submitvalue},
dataType: 'json',
success: function(response) {
}
});
for more information see here:
http://joomlabuzz.com/blog/27-preventing-cross-site-request-forgery-in-joomla
https://docs.joomla.org/How_to_add_CSRF_anti-spoofing_to_forms

Resources