3

I wish to encode an array of objects using JQuery.param() to then send the data via an ajax GET request.

The object is of type object and when doing console.log(JSON.stringify(obj)) i get:

[{"k":48.88975598812273,"B":2.362097778320276},{"k":48.88975598812273,"B":2.217902221679651},{"k":48.85023620829814,"B":2.217902221679651},{"k":48.85023620829814,"B":2.362097778320276},{"k":48.88975598812273,"B":2.362097778320276}]

When using JQuery.param(obj), it returns each value as undefined:

undefined=&undefined=&undefined=&undefined=&undefined= 

I have read similar posts whereby an array of objects is incorrectly formed, however cannot see how this is malformed.

Can anyone advise?

Ben
  • 6,026
  • 11
  • 51
  • 72

1 Answers1

5

As mentioned in the documentation for jQuery.param(), the array of objects must be in the specific format returned by .serializeArray().

jQuery.param() builds the parameter string using the "name" and "value" keys of each Object in the array. Your objects only have "k" and "B" keys, so they aren't serialized correctly.

frankjwu
  • 124
  • 1
  • 2
  • 6
  • Thanks for the comment Frank. Just so I am 100% clear, are you suggesting that the format actually has to include keys named "name" and "value"? The jQuery.param() docs page you linked to shows many examples that do not conform to this naming convention. Apologies if I have misunderstood. – Ben Jul 31 '14 at 01:23
  • @Ben Yes. The examples that do not conform to the convention are not arrays of objects. They are objects where the values are also objects. If you want to serialize an array using jQuery.param(), the objects in the array must follow that specific format. – frankjwu Jul 31 '14 at 01:29
  • For example, you can serialize the following object: `{ 1: {"k":48.88975598812273,"B":2.362097778320276}, 2: {"k":48.88975598812273,"B":2.217902221679651}, 3:{"k":48.85023620829814,"B":2.217902221679651}, 4:{"k":48.85023620829814,"B":2.362097778320276}, 5:{"k":48.88975598812273,"B":2.362097778320276} }` – frankjwu Jul 31 '14 at 01:33