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?

1 Answer 1

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}
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Understandable. This stack overflow explains the second link in my answer. Let me know if setting traditional = true works.
Traditional = true doesn't work, these are the params the server receives: {"foo"=>"[object Object]", "array"=>"[object Object]"}
Thanks. I just ended up doing something a bit hacky so both cases work.

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.