3

I have an array in my show.html.erb page and want to pass it from javascript to a method in the Controller using an Ajax request , But it gives me error HTTP/1.1 422 Unprocessable Entity Can't verify CSRF token authenticity and i have no clue where to search

here my log:

Started PUT "/new_surveys/submit" for 127.0.0.1 at 2014-05-15 19:26:12 +0200
Processing by NewSurveysController#update as JSON
Parameters: {"arrays"=>["valueSelected"], "id"=>"submit", "new_survey"=>{}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 15ms

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

here is a part of my route file that handle this part

resources :new_surveys
put "/new_surveys/submit", to: 'new_surveys#submit'

my controller , after searching most of the answers was just add skip_before_filter but it was there from the beginning and same error

class NewSurveysController < ApplicationController
  before_action :set_new_survey, only: [:show, :edit, :update, :destroy, :submit]
  skip_before_filter :verify_authenticity_token, only: [:submit]

# GET /new_surveys
# GET /new_surveys.json
def index
  @new_surveys = NewSurvey.all
end

def submit
  data = params[:arrays]
  some code ..
end

here is my AJAX call in the javascript of the show.html.erb :

function create_ajax_request (url, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('PUT', url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.setRequestHeader('Accept', 'application/json'); // I want JSON 
  xhr.responseType = "json";
  xhr.addEventListener('load', function() {
    xhr.responseJSON =  xhr.response;
    console.log(xhr.responseJSON);
    callback(xhr.responseJSON,  xhr);
   });
  xhr.send( JSON.stringify(data) );
  return xhr;
}

function submit()
{
  var SelectedValue = [];
  var name = 0;
  var radios = document.getElementsByTagName("input");
  for(var i=0; i<radios.length; i++) {
    if(radios[i].checked)
  {
  var valueSelected = radios[i].value;
  window.alert(valueSelected);
  SelectedValue.push("valueSelected")
  }
}
  var url = ['http://' + location.host, 'new_surveys', 'submit'].join('/');
  var callback = function(responseJSON, xhr) {
}
   create_ajax_request(url, {arrays: SelectedValue}, callback);
}

solved in the comments below , just had to remove auto generated methods that was created by scaffolding that was creating objects for the show , update .. etc

1
  • 2
    do you have <%= csrf_meta_tags %> in your layout header? Commented May 16, 2014 at 1:06

2 Answers 2

1

You need to send the header in your ajax request.

var metaTags = document.getElementsByTagName('meta');
for ( var i = 0; i < metaTags.length; i++) {
  if (metaTags[i].name === 'csrf-token') {
    xhr.setRequestHeader('X-CSRF-Token', metaTags[i].content);
  }
}

Using the ajax functionality via the jquery-rails gem will give you this for free :)

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using jquery-rails gem and still experience a similar problem.
Did you try setting the header? If you're creating your own ajax requests, you need to setup the header. jquery-rails handles it for you with :remote => true links & forms, but if you do your own ajax call you have to add it. You can of course simplify my above example by using jquery to grab the meta tag.
1

solved

just had to remove auto generated methods that was created by scaffolding that was creating objects for the show , update .. etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.