sakshik12 sakshik12 - 1 year ago 113
jQuery Question

dropzone in a form - InvalidAuthenticityToken

I am using drop zone as part of a form. ie. the form has other elements apart from just the dropzone field. Also, no new view is loaded after form submission, just some js code so remote = true. The form looks like this:

<%= form_tag submit_form_path, method: "POST", "data-abide" => "", 'autocomplete' => 'off', id: "id-of-form", remote: true, multipart: true do %>

<div class="dropzone" id="myDropzone"></div>
<%= text_field_tag "name", ....
<%= text_field_tag "number", "", ....
<%= text_field_tag "email", "", ....
<%= submit_tag "submit", id: "submit-button" ....

<% end %>


Dropzone.options.myDropzone = {
url: '/submit_form',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
dzClosure = this;

// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit-button").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.

//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("name", jQuery("#name").val());
*the rest of the form elements*


On submitting the form I get
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 2ms

Solved invalid authenticity token problem. However, now Im getting an
ActionView::MissingTemplate - Missing template
Before dropzone was added to the form. I was successfully able to submit the form and execute some js code (submit_details.js.erb) without reloading the page.

But now its

Processing by XyzController#submit_details as JSON


ActionView::MissingTemplate - Missing template xyz/submit_details, application/submit_enquiry with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :arb, :jbuilder]}.

Answer Source

try adding the header to your Dropzone request

Dropzone.options.myDropzone = {
  url: '/submit_form',
  autoProcessQueue: false,
  headers: {
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')