Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  147] [ 4]  / answers: 1 / hits: 192479  / 10 Years ago, thu, february 27, 2014, 12:00:00

I need to pass CSRFToken with Ajax based post request but not sure how this can done in a best way.
Using a platform which internally checking CSRFToken in request (POST request only)



initially I was thinking to add it to header like



$(function() {
$.ajaxSetup({
headers : {
'CSRFToken' : getCSRFTokenValue()
}
});
});


Which will make it available to each Ajax request, but it will not work for my case, since in request CSRFToken is still coming as null.



Is there any way I can set CSRFToken for all Ajax call dealing with POST type



Edit
If I do something like this in my Ajax call



data: {newsletter-subscription-email : XXX , 'CSRFToken': getCSRFTokenValue()},


Everything is working fine.



My Issue is, I want to pass CSRFToken value as a request parameter and not as a request header


More From » jquery

 Answers
6

How about this,



$(body).bind(ajaxSend, function(elm, xhr, s){
if (s.type == POST) {
xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
}
});


Ref: http://erlend.oftedal.no/blog/?blogid=118



To pass CSRF as parameter,



        $.ajax({
type: POST,
url: file,
data: { CSRF: getCSRFTokenValue()}
})
.done(function( msg ) {
alert( Data: + msg );
});

[#72277] Wednesday, February 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;