sending parameters with brackets [ ] via AngularJS

By: Johnathon Wright on: December 06, 2013

I want an AngularJS controller to POST to a Rails endpoint with parameters like { 'item[price]': '32.50' } and have Rails see it as "item" => {"price": "32.50"}. This works perfectly well in normal HTML... it's not clear why it isn't working in Angular.

Via HTTP

It works in a normal HTML form:

<form action="/items.json" method="POST">
  <input name="item[price]" type="text" value="32.50" />
  <input type="submit">Save</input>
</form>

submitting this form, we see this from Rails:

Started POST "/items.json" for 192.168.1.20 at 2013-12-06 09:47:04 -0600
Processing by ItemsController#create as JSON
Parameters: {"item"=>{"price"=>"32.50"}}

via $http.post

$http.post('/items.json', {'item[price]': '32.50'});

and Rails sees:

Started POST "/items.json" for 192.168.1.20 at 2013-12-06 09:50:39 -0600
Processing by ItemsController#create as JSON
  Parameters: {"item[price]"=>"32.50", "item"=>{"item[price]"=>"32.50"}}

So what's different?

Checking Chrome's developer tools, under the network tab > Headers, we get some answers

When using a form, I see a section labeled "Form Data". After clicking "View Source" I get this:

item%5Bprice%5D=32.50

When using AngularJS, I see a section labeled "Request Payload". After clicking "View Source", I get this:

{"item[price]":"32.50"}

AH HA!

Final Solution

$scope.submit_data = function()
{
    var xsrf = $.param({'item[price]': '32.50'});

    $http.post('/items.json',
      xsrf,
      {headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}}
    );
}

References

"What is the difference between form data and request payload?"

How can I make angular.js post data as form data instead of a request payload?





Comments:

Just checking that you are human. What would be the result of this code?

a = 3*(4/2); b = 1; a+b

Jack said: As a service provider, one of the most common questions you may encounter is, "How far in advance should I book your services?" It's a valid question, and the answer truly depends on the type of service you offer and the demand for it. New Jersey Motorcycle Shipping Services

Back