website
website copied to clipboard
Howto use Ajax calls using csrf token
We should add how to make ajax calls with the csrf token in the documentation. Something along the line of https://gist.github.com/benschwarz/5333009
Here's how I handle it (I had to use jquery in that project):
// csrf.js
import $ from "jquery";
const Csrf = () => {
const token = $("meta[name=\"csrf-token\"]").attr("content");
$.ajaxSetup({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-CSRF-Token", token);
}
});
};
export default Csrf;
// app.js
import Csrf from "./csrf.js";
Csrf();
Thanks! That's super helpful
Here's a non-jQuery version for JS submitting to end-points in Lucky. I use this in Stimulus controllers often.
let csrf_token = document.querySelector('[name="csrf-token"]').content
fetch('/path/in/your/app/', {
method: 'POST',
headers: { 'x-csrf-token': csrf_token },
body: JSON.stringify({ // use valid JSON here to post anything })
}).then(response => response.json()) // Do whatever you want with the json response object here.
Here's what a GET request would look like. I think you could also omit the "method: 'GET" part and just define the headers, but I prefer to be explicit about it.
let csrf_token = document.querySelector('[name="csrf-token"]').content
fetch('/path/in/your/app/', {
method: 'GET',
headers: { 'x-csrf-token': csrf_token })
}).then(response => response.json()) // Do whatever you want with the json response object here.