[JS] Utilizing .serialize to build a post data str

Joe Huss

Administrator
Staff member
in general in JS and building urls to submit get or post data with from form elements , instead of directly building the post data string and having to encodeURIComponent each input.. you can replace all that with a simple $(form).serialize() call.
for example
like I see htings like this a lot
"ajax=1&tos=" + encodeURIComponent(jQuery("#tos").val()) + "&login_id=" + encodeURIComponent(jQuery("#login_id").val())
could be replaced with like $('form').serialize()
here are some more examples showing advanced usages
// all form elemenets
$("form").serialize();
// all select elements and input elements that dont have the .login_info class
$('#loginForm input:not(.login_info), #loginForm select').serialize();
// combine inputs from diff forms
$('#loginForm input:not(.login_info), #loginForm select:not(.login_info), #ccform input').serialize()
// combine 3 diff forms
jQuery('#step2form, #step3form, #step4form).serialize();
Note: Similarly you can also parse them into an array with 'name' and 'value' elements in each row with .serializeArray()
 
Top