0

Have the following Ajax request:

data = {foo: {id: 1}, 
        array: [
                {id: 2, date: "Jan  1, 2015", quantity: 100}
               ]}

$.ajax "/api/foo",
  type: "POST",
  dataType: "JSON"
  data: data,
  success: (data) ->
    console.log(data)

The issue is that the server gets the following params:

{foo: {id: 1}, 
 array: { 
         0:{id: 2, date: "Jan  1, 2015", quantity: 100}
 }}

As you can see the array is transformed into a hash with incremental keys. Why isn't the data being received as I sent it?

Curt
  • 325
  • 1
  • 3
  • 12

1 Answers1

1

According to the AJAX docs this is the expected behavior.

data

Type: PlainObject or String or Array

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

You can play with the traditional setting that is mentioned in the docs to try to get the exact same representation though you should be able to use this as it is.

In your controller, you should be able to do the following params[:array][0] or params[:array].each ... to access the data. You're still getting a response that Ruby can handle like an array. If there were more records in this array it would look like this.

array: { 
  0:{id: 2, date: "Jan  1, 2015", quantity: 100}
  1:{id: 3, date: "Jan  1, 2015", quantity: 200}
  2:{id: 4, date: "Jan  1, 2015", quantity: 300}
}
Community
  • 1
  • 1
James Klein
  • 612
  • 4
  • 15
  • The end point is accessed via multiple methods and I wanted to have a standardized format. Thus I'm trying to get the array to pass properly. – Curt Feb 24 '16 at 20:32
  • Understandable. [This stack overflow](http://stackoverflow.com/questions/5497093/what-is-traditional-style-of-param-serialization-in-jquery) explains the second link in my answer. Let me know if setting `traditional = true` works. – James Klein Feb 24 '16 at 20:40
  • Traditional = true doesn't work, these are the params the server receives: {"foo"=>"[object Object]", "array"=>"[object Object]"} – Curt Feb 24 '16 at 20:51
  • Thanks. I just ended up doing something a bit hacky so both cases work. – Curt Feb 24 '16 at 20:57