Twitter: raymondcamden


Address: Lafayette, LA, USA

Quick Sample: Appending URL data to a Form post with JavaScript

12-11-2013 6,445 views Development, JavaScript 6 Comments

This is a quick sample based on a request from a reader. They have a form that is loaded with a dynamic value in the query string. They were curious if there was a simple way to pass along the query string data along with the form post data. There's a couple different ways of handling this. Here is my version.

First - let's build up a simple form. In my HTML I'm including jQuery and a JavaScript file called app.js where I'll do the actual logic.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title></title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width">
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
		<script src="app.js"></script>
	</head>
	<body>
		
		<form id="theForm">
			<p>
			<label for="name">
				Name
			</label>
			<input type="text" id="name" name="name">
			</p>
			<p>
			<label for="email">
				Email
			</label>
			<input type="email" id="email" name="email">
			</p>
			<p>
			<input type="submit" name="Send Form">
			</p>
		</form>
	</body>
</html>

There isn't anything special about the form so let's get right into the JavaScript. Let me repeat though - this is my solution - and is one of several different ways we could accomplish the task.

/* global window,$,document */
function getQueryString() {
	var result = {};
	if(!window.location.search.length) return result;
	var qs = window.location.search.slice(1);
	var parts = qs.split("&");
	for(var i=0, len=parts.length; i<len; i++) {
		var tokens = parts[i].split("=");
		result[tokens[0]] = decodeURIComponent(tokens[1]);
	}
	return result;
}

$(document).ready(function() {
	$("#theForm").submit(function(e) {
		//var that = this;
		var qs = getQueryString();
		for(var key in qs) {
			var field = $(document.createElement("input"));
			field.attr("name", key).attr("type","hidden");
			field.val(qs[key]);
			$(this).append(field);
		}
	});
});

Ok, let's break it down. The core of the logic is inside a form submit handler. The idea being that when you submit the form we want to grab the query string and pass it along. I built a simple handler to get the query string and return it as a set of keys and values.

So now we have an easy way to get the query string. But what do we do with it? I see two possible options (and there are probably more).

The first option would be to take the query string values, convert them to JSON, and store them in a hidden form field. On the server you would deserialize the JSON and use the values as is. This has the benefit of allowing you to separate the form data from the query string data. That may be important to you.

The second option (and again, I'm assuming there are many more) would be to convert the query string values into form fields. This has the benefit of giving you one set of values to work with on the server side. That's simpler and could be better for your logic there. A drawback though is that if a query string value had some name, X, that matched an existing form key, you'll get some duplication.

For simplicity sake, I went with the second option. You can see that I simply create hidden form fields and append them to the form. Since my HTML doesn't use POST as a method, you can see this for yourself by using the demo below. I've added two items to the query string. When you submit the form, they will carry over.

6 Comments

  • Commented on 12-11-2013 at 12:07 PM
    Wouldn't it be a little less code to just use the CGI Query_String? I use this all the time...
  • Commented on 12-11-2013 at 12:40 PM
    @John: Because this isn't ColdFusion. :)
  • Max Moore #
    Commented on 12-11-2013 at 1:30 PM
    If they have the flexibility to edit the HTML, they could also just add the hidden input there. If they are populating any fields at load, might be easier to populate the hidden at the same time and skip trapping submit event.
  • Commented on 12-11-2013 at 1:34 PM
    @Max: Even with the hidden field, they need a submit handler to capture the query string. That's just my option 1 above, right?
  • Commented on 12-11-2013 at 3:25 PM
    You might want to unescape the query string elements after splitting on the "=" sign.
  • Commented on 12-11-2013 at 4:07 PM
    Oops, good point. Added. Editing the blog post right now but the demo is updated. Thanks Michael!

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty