Search code examples
ruby-on-railsjsonangularjsangular-http

Problems parsing parameters from Angular post in Rails controller


I have an Angular.js app that sends a POST request to a Rails server endpoint and I'm having trouble passing and reading the parameters.

This is how I send the data

$scope.submitForm = function(info) {

    $http({
      method: 'POST',
      url: app.apiServerUrl + '/complaints/create',
      data: info,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, headers, config) {

      // this callback will be called asynchronously
      // when the response is available
    }).error(function(data, status, headers, config) {
     // called asynchronously if an error occurs
     // or server returns response with an error status.

  });
};

The info object passed is a object in the form: { title: "something", ocurrence_place: "something" }.

And in my controller create action I have this:

def create
  p params
  p params[:title]
end

but this is what gets printed in the logs

{"{\"title\":\"foo\",\"ocurrence_place\":\"bar\"}"=>nil, "controller"=>"complaints", "action"=>"create"}
nil

So, as you can see, I can't access params hash attributes. How can I fix this so the controller in my controllers works and prints what is expected?


Solution

  • It looks to me like your info object isn't really an object but a string of JSON.

    Try changing data: info to data: JSON.parse(info) or correcting whatever is calling submitForm(info) so that the info argument is really a object.