Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing array of objects from js to rails

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"}] 
like image 449
Tabraiz Ali Avatar asked Jul 03 '16 23:07

Tabraiz Ali


2 Answers

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.

like image 143
max pleaner Avatar answered Oct 21 '22 21:10

max pleaner


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"
});
like image 42
Aetherus Avatar answered Oct 21 '22 23:10

Aetherus