I have a jQuery ajax function and would like to an entire form as post data. We are constantly updating the form so it becomes tedious to constantly update the form inputs that should be sent in the query.
A:
Use
var str = $("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
rahul
2010-01-07 10:40:07
+4
A:
There's a function that does exactly this:
http://docs.jquery.com/Ajax/serialize
var data = $('form').serialize();
$.post('url', data);
Will Vousden
2010-01-07 10:40:37
A:
In general use [].serialize() on the form element.
Please be mindful that multiple <select> options are serialize()'d under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that looks like
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
prometheus
2010-01-07 12:24:15