1

i have some html snip like this

<input type="checkbox" name="color" value="red"/>red
<input type="checkbox" name="color" value="green"/>green
<input type="checkbox" name="color" value="purple"/>purple
<input type="checkbox" name="color" value="grey"/>grey

and i want to use jquery to post value to server, so i used jquery like this

$.post('/test', {'color': ['red', 'green']});

i did search this question in stackoverflow, but people say it's should be 'color[]' instead of 'color', but whenever i used 'color' or 'color[]' firebug displayed the post data is 'color%5B%5D=red&color%5B%5D=green', and my server can't work right, but when using

<input type="submit" value="submit"/>

to post firebug says the data is 'color=red&color=green', and my server work right. How could it be? my jquery version is 1.4.4

1
  • have you tried with jQuery.ajax() ..? Commented Aug 2, 2011 at 12:52

2 Answers 2

2

I believe that when you call -

$.post('/test', {'color': ['red', 'green']});

an array is being passed as the post data and the flattening of the array is what's causing the 'color%5B%5D=red&color%5B%5D=green' result.

If you use the following -

$('input:checkbox[name="color"][checked=true]').serialize()

This should return all of the checked checkboxes in the 'color=red&color=green' format. There's a jsfiddle that attempts to illustrate the concept here - http://jsfiddle.net/789nP/.

Sign up to request clarification or add additional context in comments.

Comments

1

For some reason, the jQuery developers decided that PHP's bizarre handling of multiple controls with the same name is The Correct Way. As a consequence, when submitting an array of data, jQuery will append [] to the name (%5B%5D is just a URL encoded representation of []).

to post firebug says the data is 'color=red&color=green', and my server work right

That suggests that you are using something other than PHP to process the data so PHP's magic handling of [] in names does not apply.

You can either look for color[] on the server…

e.g.

@values = $query->param('color[]');

… or you can set traditional mode to stop jQuery PHPifying your data.

$.post('/test', {'color': ['red', 'green']}, { traditional: true });

Then normal access should work:

@values = $query->param('color');

2 Comments

Thanks for that answer, I'd never really understood why jQuery was flattening the array in the way that it does. It all makes sense now!
Ok, that's right, and i used php to test again, it really works! BTW, I'm using web.py as my server...maybe i should learned some php right now, LOL

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.