csrf validation in yii2 not working - ajax

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()
};

Related

Passing ID to Controller using Ajax - Error 404 in Laravel

I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}

CSRF token mismatch while uploading image using ajax in CakePHP 3.6

I have tried
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
$this->getEventManager()->off($this->Csrf);
}
public function ajaxEdit($id = null)
{
$this->autoRender = false;
debug($id);
debug($this->request->getData());
}
And I am using ajax code
$(document).ready(function(){
$('#user-profile').change(function(){
$('.loader-body').show();
var form = $('#user-profile-image')[0];
var formData = new FormData(form);
var tutorial_id = $('#user-file-id').val();
$.ajax({
url :"/users/ajax-edit/"+tutorial_id,
method:"POST",
data:formData,
contentType:false,
cache: false,
processData:false,
success:function(data){
let parseData = $.parseJSON(data);
if (parseData.status === true) {
location.reload();
var value = parseData.url;
console.log(value);
} else {
alert(parseData.message);
}
}
});
});
});
I have followed help from these links
CakePHP ajax CSRF token mismatch
2 https://book.cakephp.org/3.0/en/controllers/components/csrf.html
Getting CSRF token mismatch (see attached image)
https://i.stack.imgur.com/FsVZu.png
First of all if your are using POST method in your ajax call then you should send tutorial_id as data instead of sending it in the url.
You can resolve this by sending you CSRF token through a special X-CSRF-Token header in your ajax call.
https://book.cakephp.org/3.0/en/controllers/components/csrf.html
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
OR
You can disable CSRF component[Not recommended by the Cakephp] for your ajax action like:
public function beforeFilter(Event $event) {
if (in_array($this->request->action, ['ajaxEdit'])) {
$this->eventManager()->off($this->Csrf);
}
}

How to send json serialize data from a form to ajax using django

Currently, I'm sending the data via code in this way and it's working but how can I send the entire form in json?
Code :
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
email : email,
password : password,
username : username,
dob : dob,
}, // data sent with the post request
I want to send and retrieve everything including csrfmiddlewaretoken using formdata json.
I have tried something similar to that :
var formData = new FormData($('#my_form');
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : formData, // data sent with the post request
But, this does not work for some reason. How can I get it to work?
you need to send json serialized form data as one paramater and csrf token as another parameter because every POST request expects a csrf token in it.
csrfmiddlewaretoken = $("#add_member_Form").find("input[name='csrfmiddlewaretoken']" ).val();
formData = $('#add_member_Form').serializeArray();
formData = JSON.stringify(formData);
$.ajax({
url : url,
data : {
"csrfmiddlewaretoken" : csrfmiddlewaretoken,
"formData" : formData
},
method: "POST",
dataType : "json",
At server side in your view, you need to deserialize the data.
form_data_dict = {}
form_data_list = json.loads(form_data)
for field in form_data_list:
form_data_dict[field["name"]] = field["value"]
return form_data_dict
You could grab the form data usingserializeArray function in jQuery, then convert it into dictionary and send as post data.
The serializeArray function output would be something like,
{
'name': 'the_name',
'value': 'the_value'
}
Then, you would have to convert it to the dictionary or json format. Write a global function for that,
function objectifyForm(formArray) {
var returnArray = {};
for (var i=0;i<formArray.length;i++) {
if (formArray[i].value) {
returnArray[formArray[i].name] = formArray[i].value;
}
}
return returnArray;
}
Call it whenever you have to grab the form data,
var formData = $('#my_form').serializeArray();
formData = objectifyForm(formData);
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : formData,
success: blaah,
error: bleeh,
});
It would be much less effort than having to decode the dictionary every time from the server side.

updation issue during with ajax method

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')}});

how to send an object from spring controller to jsp through Ajax

I have a transaction object and I am trying to send the object to the front page. I have no problem when I try to send a string, but I couldn't send an object.
So this is my controller:
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET)
#ResponseBody
public MyTransaction helloahjax() {
System.out.println("hello Ajax");
MyTransaction tran = MyTransaction.getInstance();
tran.setId(123);
return tran;
}
#RequestMapping(value="/result", method=RequestMethod.GET)
public String show() {
return "result";
}
and this is my ajax call
button
<div class="result"></div>
function doajax() {
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
$('.result').html(response.id);
},
error: function() {
alert("asda");
}
});
};
I search around and see that other developers used "response.result.id" but I couldn't make it neither. Any suggestion please.
I would suggest to change your code like below.
1.Include JSON library to your classpath and add produces="application/json" attribute to RequestMapping for the helloahjax method.
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET,produces="application/json")
2.Include dataType in your ajax call,like below
$.ajax({
type : 'GET',
dataType : 'json',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
var obj = JSON.parse(response);
//Now you can set data as you want
$('.result').html(obj.id);
},
error: function() {
alert("asda");
}
});
The URL would change to below when you are returning JSON from the controller method. In this case you don't need to parse the response. Instead you can directly access the object variables as response.abc
${pageContext.request.contextPath}/result/helloajax.json

Resources