Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created July 2, 2015 13:43
Show Gist options
  • Save zmajstor/238f567466443e4c9f02 to your computer and use it in GitHub Desktop.
Save zmajstor/238f567466443e4c9f02 to your computer and use it in GitHub Desktop.
Ajax in Rails View with X-CSRF-Token
<%= check_box_tag "foo[delivered]", nil, foo.delivered, data: { id: foo.id }, class: "delivered" %>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token': '<%= form_authenticity_token.to_s %>' },
timeout: 30000, // timeout after 30 seconds
async: true,
cache: false,
// dataType: "json", // The type of data that you're expecting back from the server
});
$(document).on( "change", ".delivered", function() {
var sendData = { id: $(this).data('id'), delivered: $(this).prop('checked')};
$.ajax({
type: 'PATCH',
url: '<%= ajax_path %>',
data: sendData,
}).done( function (data, status) {
return true;
}).fail( function (data, status) {
alert("update server error: " + data.status + ' ' + data.statusText + '\n' + data.responseText);
return false;
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment