Ajax: Form fields into URL query string

Javascript code to parse form fields into URL query string. To be used with Ajax sites.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Here’s a quickie for you Ajax coders who need a function to parse your form fields into a URL query string. It handles input fields (text, hidden, whatever), radio and checkbox elements, and single/multiple select menus. Just make sure that all your form fields have IDs. Multiple choice SELECTs get grouped by pipes (|). Update:Modified multiple-choice SELECTs to work like real GETs.

function build_post_string(frm) {
	var poststr;
	var poststr_array = [];
	if (!frm.id) {
		// assume it's a string. get the form object
		frm = document.getElementById(frm);
	for (i=0;i<frm.elements.length;i++){

		var elem = frm.elements;
		if (!elem.id) {
			// skip any fields that don't have IDs
		if (elem.type == 'radio' || elem.type == 'checkbox') {
			// only grab radio buttons and checkboxes that are checked
			if (!elem.checked) {
		// get select values
		if (elem.nodeName.match(/SELECT/i) && elem.multiple) {
			//var sel = elem;
			var sel_array = new Array();

			for (var o=0;o<elem.options.length;o++) {
				if (elem.options[o].selected) {
					sel_array[sel_array.length] = elem.id+"="+elem.options[o].value;	
			var sel_str = sel_array.join('&');
			// build key/value pairs for SELECTs
			poststr_array[poststr_array.length] = sel_str;
		else if (elem.nodeName.match(/SELECT/i)) {
			poststr_array[poststr_array.length] = elem.id+'='+elem.options[elem.selectedIndex].value;
		else {
			// build key/value pairs for everything else
			poststr_array[poststr_array.length] = elem.id+"="+elem.value;

	// build poststr
	poststr = poststr_array.join("&");
	return poststr;


Book Suggestions:


More To Explore


bbPress Notify (No-Spam) Documentation

bbPress Notify (No-Spam) Documentation The bbPress Notify (No-Spam) is a free plugin that lets you control who gets notifications of new Topics and Replies in

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.