Edwardo S Edwardo S - 1 year ago 220
Ajax Question

How to add csrf token to ajax request

I have issues adding csrf to ajax request. I'm using thymeleaf on client side with spring-boot/spring security. Spring security wouldn't allow the request because csrf-token is missing. Here is my code for ajax

function bits(){
var xhttp = new XMLHttpRequest();
var selected = document.getElementById("product").value;
xhttp.onreadystatechange = function(){
if(xhttp.readyState==4 && xhttp.status==200){
var result= JSON.parse(xhttp.responseText)
var length = result.length;
for(i=0; i<length; i++){



xhttp.open("POST", "http://localhost:8080/bids?q="+selected, true);


Help will be appreciated

Answer Source

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);
xmlhttp.setRequestHeader(header, token);

Hope this helps someone too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download