Posting Objectified Data Using jQuery

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Posting Objectified Data Using jQuery

Post by JellyFish »

jQuery question. This:

Code: Select all

$.post('somepage.php', {key:'value'});
makes sense. However, this:

Code: Select all

$.post('somepage.php', {key:['array','value']});
doesn't to me. What does it mean to send data like this? I thought that the object was turned into a query string like:

[text]key=value&...etc[/text]

What does it mean to send a key which equals an array? As far as I know, a query string can't contain a set of key/values for a key:

[text]key=[arrary,value]&...[/text]

Can it? Will someone please shed some light on this?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Posting Objectified Data Using jQuery

Post by Weirdan »

What does it mean to send a key which equals an array?
jquery would then pass multiple instances of key, one for each value:

Code: Select all

key=array&key=value
This is mostly useless, unless you use php's array notation for urlencoded data:

Code: Select all

$.post('somepage.php', {'key[]':['array','value']});
If you do, it will look like an array to the receiving php script.
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Re: Posting Objectified Data Using jQuery

Post by JellyFish »

Oh so if you set a key twice in the query string, the server script (php) will receive it as an array?

Useful notation in jQuery. However, why must it be:

Code: Select all

$.post("/", {'key[]':['value1', 'value2']}):
and not just

Code: Select all

$.post("/", {'key':['value1', 'value2']}):
???
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Posting Objectified Data Using jQuery

Post by Weirdan »

JellyFish wrote:Useful notation in jQuery. However, why must it be:

Code: Select all

$.post("/", {'key[]':['value1', 'value2']}):
and not just

Code: Select all

$.post("/", {'key':['value1', 'value2']}):
???
Because you need to name your field names with [] postfix for php to recognize them as arrays. And jQuery not doing this for you because it's not limited to php-backed sites.
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Re: Posting Objectified Data Using jQuery

Post by JellyFish »

Oh, so then the actual post data will look like:

[text]key[]=value1&key[]=value2[/text]

correct?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Posting Objectified Data Using jQuery

Post by Weirdan »

JellyFish wrote:correct?
Yep.
Post Reply