Phoenix - invald CSRF on AJAX post
This is because Phoenix does not create a meta tag with the CSRF token by default. They're only included in forms generated by Phoenix's helper functions, and they're in a hidden input.
To get a CSRF token programatically in Phoenix, you can call Plug.CSRFProtection.get_csrf_token/0
. There are many ways to pass this to your JS. You can add a meta tag to your layout to include it in every page but that might not be very efficient since it'll be generated for all pages. You can also just store it in a JS variable in the views that you require them in:
<input type="text" id="raw-input" />
<button id="send-button">Send it!</button>
<script>
$("#send-button").click(function(){
var CSRF_TOKEN = <%= raw Poison.encode!(Plug.CSRFProtection.get_csrf_token()) %>;
var input = $("#raw-input").val();
$.ajax({
url: "/test/process",
type: "POST",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", CSRF_TOKEN);
},
data: {"input" : input},
success: function(response){
console.log(response);
}
});
});
</script>
Phoenix already has helper csrf_meta_tag. Include it in the layout like so:
<html lang="en">
<head>
<%= csrf_meta_tag %>
...
And then use it in your js like so: $("meta[name='csrf-token']").attr("content")