tags:

views:

38

answers:

1

What is the recommended way in JQUERY to send a dynamic set of data to the server, the set contains items like:

ID: 13 Copy:

hello world....hello world....hello world....hello world....

ID: 122 Copy:

Ding dong ...Ding dong ...Ding dong ...Ding dong ...Ding dong ...

ID: 11233 Copy:

mre moremore ajkdkjdksjkjdskjdskjdskjds

This could range from 1, to 10 items. What's the best way to structure that data to post to the server with JQUERY?

Thanks

+1  A: 

A JSON array. Note that this is the string representation of a JavaScript array.

'[
   {"ID": 13,
   "Copy": "hello world....hello world....hello world....hello world...."},
   {"ID": 122,
   "Copy": "Ding dong ...Ding dong ...Ding dong ...Ding dong ...Ding dong ..."},
   {"ID": 11233,
    "Copy": "mre moremore ajkdkjdksjkjdskjdskjdskjds"}
 ]'

You can create this programatically using something like::

var array = [];
for(...)
{
  var newEl = {};
  newEl.ID = ...
  newEl.Copy = ...
  array.push(newEl);
}

var jsonText = JSON.stringify(array);

You then pass jsonText as the data parameter to $.ajax.

Matthew Flaschen
That shouldn't be a string.
SLaks
Suggestions for how to create a JSON array?
AnApprentice
SLaks don't you have to serialize it to send it through GET or POST? I usually do...
Alex Mcp
@Alex please say more :)
AnApprentice
@SLaks, @Alex, yes, it needs to be stringified, and jQuery does not handle this for you.
Matthew Flaschen
SLaks
@SLaks, no. I got misled by those same docs before. It does have to be. It won't encode an object to JSON, even if you specify application/json as the request content type. See this [JSFiddle demo](http://jsfiddle.net/EnPHC/3/).
Matthew Flaschen
From the source: `// convert data if not already a string if ( s.data }`
SLaks
@SLaks, jQuery.param converts to a type of URL-encoded string, *not* JSON. Take a look at the demo. It serializes the array to the junk value "undefined=undefined".
Matthew Flaschen