Search code examples
ruby-on-railsjsonajaxcsrfsurvey

How to succesfully save a json object recieved as POST- ruby on rails


I'm trying to create an app that allows user to submit reviews.

I used survey.js which returns a json object with the responses, here is the coffee script file which sends the request to the desired url:

$.ajax({
  type:'POST',
  url: "/surveys/save",
  data: survey.data,
  success: alert("saved"),
  dataType: JSON

And in my Controller I try to save the appropriate parameters:

def create
    if validate_user
      @submission = Submission.new(submission_params)
      if @submission.save
        redirect_to '/surveys/saved'
      else
        redirect_to '/surveys/nosaved'
      end
    end
end

However I see this output from the server:

"Started POST "/surveys/save" for ::1 at 2016-08-01 00:21:47 -0400
Processing by SurveysController#create as */*
  Parameters: {"question1"=>"eh", "question2"=>"1", "question3"=>"3", "question4"=>"1", "question5"=>"1", "question6"=>"3", "question7"=>"4", "question8"=>"1", "question9"=>"2", "question10"=>"1"}
Can't verify CSRF token authenticity"

Please advise, from my research it seems that I need to prepend the authenticity token to my request but i'm not sure how to go about that.

Thanks!

****UPDATE**

I do have the CSRF meta tag in my application layout file

******UPDATE 2*******

I tried the following in the Coffee script, it resulted in the same output.

$.ajax({
  type:'POST',
  beforeSend: test = (xhr)-> return xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf token"]').attr('content'))
  url: "/surveys/save",
  data: survey.data,
  success: alert("saved"),
  dataType: JSON


  });

Solution

  • The solution was as Abid attempted to do, but by just declaring the header as such in the coffee script.

      $.ajax({
        type:'POST',
        headers: {'X-CSRF-Token': $('meta[name="csrf token"]').attr('content')},
        url: "/surveys/save",
        data: survey.data,
        success: alert("saved"),
        dataType: JSON
        })