Adding Csrftoken to Ajax Request

Adding CSRFToken to Ajax request

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

How to automatically add X-CSRF-TOKEN with jQuery ajax request in Laravel

In Laravel the value of the csrf-token meta tag registers by default with the Axios HTTP library. But If you are not using this library, you will need to manually configure this behavior for your application.

To do this, store the token in a HTML meta tag

<meta name="csrf-token" content="{{ csrf_token() }}">

Then, once you have created the meta tag, you can instruct the jQuery library to automatically add the token to all the request headers.

For that add the code to the resources/js/bootstrap.js file for Laravel 5.7 and resources/assets/js/bootstrap.js for Laravel 5.6 and below versions.

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Ajax without csrf token as it will get added automatically

$.ajax({
type:'post',
url: "/email/unique",
data: { "email": email }
success: function(data) {
console.log(data);
}
});

How to pass along CSRF token in an AJAX post request for a form?

Ok, after fighting this for a few hours and trying to decrypt Play's frequently-lacking-context-Documentation on the subject, I've got it.

So, from their docs:

To allow simple protection for non browser requests, Play only checks
requests with cookies in the header. If you are making requests with
AJAX, you can place the CSRF token in the HTML page, and then add it
to the request using the Csrf-Token header.

And then there's no code or example. Thanks Play. Very descriptive. Anyway, here's how:

in your view.html.formTemplate you might write in IntelliJ:

@()
<form method="post" id="myForm" action="someURL">

@helper.CSRF.formField <!-- This auto-generates a token for you -->
<input type="text" id="sometext">
<button type="submit"> Submit! </button>

</form>

And this will render like this when delivered to the client:

<form method="post" id="myForm" action="someURL">

<input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">
<input type="text" id="sometext">
<button type="submit"> Submit! </button>

</form>

Ok, almost there, now we have to create our AJAX call. I have all of mine in a separate main.js file, but you could also put this in your view.html.formTemplate if you want.

$(document).on('submit', '#myForm', function (event) {

event.preventDefault();
var data = {
myTextToPass: $('#sometext').val()
}
// LOOK AT ME! BETWEEN HERE AND
var token = $('input[name="csrfToken"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
// HERE
var route = jsRoutes.controllers.DashboardController.postNewProject()
$.ajax({
url: route.url,
type: route.type,
data : JSON.stringify(data),
contentType : 'application/json',
success: function (data) { ... },
error: function (data) { ... }
})

});

With this line:
var token = $('input[name="csrfToken"]').attr('value')
You are plucking out the CSRF token auto generated in your form field and grabbing its value in a var to be used in your Javascript.

The other important chunk from all that AJAX is here:

$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});

Using the $.ajaxSetup, you can set what's in the header. This is what you have to infer from their documentation:

add it to the request using the Csrf-Token header.

Good luck! Let me know if this is clear.


Note: when using lusca, use X-CSRF-Token instead of Csrf-Token.

Django: How to send csrf_token with Ajax

This was the solution that worked for me in this case:

Added this code before the Ajax code:

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});

Django csrf token for Ajax

See below for how I changed your code. The csrf_token is assigned to a variable with Django templating. You can produce this variable in any of your Javascript code.

The token is then included in the header

 <script>
var token = '{{csrf_token}}';

$("#id_username").change(function () {
console.log($(this).val());
var form = $(this).closest("form");
$.ajax({
headers: { "X-CSRFToken": token },
url: form.attr("data-validate-username-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert(data.error_message);
}
}
});

});
</script>

Laravel csrf token mismatch for ajax POST Request

You have to add data in your ajax request. I hope so it will be work.

data: {
"_token": "{{ csrf_token() }}",
"id": id
}

AJAX request and csrf token

req = $.ajax({
url: 'updateit/',
type: 'post',
data: {
'productId' : productId,
'action' : 'plus',
csrfmiddlewaretoken:'{{ csrf_token }}',
}
});

use this,

How to add csrf token to ajax request

I modified @Prakash Hari Sharma's solution and had the following code that worked for me. Note, th: prefix if using Thymeleaf.

--Header section

<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>

Ajax script function

...
...
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
...
...
xhttp.open("POST", "http://localhost:8080/bids?q="+selected, true);
xhttp.setRequestHeader(header, token);
xhttp.send();

Hope this helps someone too.



Related Topics



Leave a reply



Submit