10

I am trying to pass an array of objects from js to rails

data.test = [{test: 'asdas'}]

$.ajax({
  url: 'evaluate.json',
  data: data,
  success: function(data){
  },
  dataType : "json"
});

Rails

def evaluate
   logger.info("#{params.test}")
end

Here the logger statement always gives me out put as

{"0"=>{"test"=>"asdas"}}

I am expecting the below log in rails.

 [{:test=>"asdas"}] 
1
  • did you solved ? Commented Nov 9, 2017 at 17:32

2 Answers 2

6

You should use JSON.stringify in Javascript, which takes either an array or hash as its argument (since these are the only valid JSON constructions). It returns a form which is the Javascript object serialized to JSON.

On the Ruby side, you'll receive a JSON encoded string, so you'll need to require 'json' (this is done automatically in Rails) and use JSON.parse(string). This will give you a Ruby object.

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

Comments

5

Try this:

data.test = [{test: 'asdas'}]

$.ajax({
  url: 'evaluate.json',
  data: JSON.stringify(data),  // Explicit JSON serialization
  contentType: 'application/json',  // Overwrite the default content type: application/x-www-form-urlencoded
  success: function(data){
  },
  dataType : "json"
});

3 Comments

yes yes yes! This is what I've been looking for for ages. Thanks. What you said and others didn't was that you need BOTH 'dataType' and 'contentType' for it to work (or I did anyway) as well as the stringified JSON. I had to add my authenticity token as well.
This answer is somewhat obsolete. You should use promise instead of the success callback.
This is exactly what I was looking for. This should be the accepted answer.

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.