1

I have an html page that people access using an affiliate link, so it has affiliate code in the url (http://www.site.com?cmpid=1234&aid=123). I want to add the cmpid and the aid to the form action url (so when submitted, it submits to the url /form.aspx but adds the cmpid and aid to the end, ie: form.aspx?cmpid=1234&aid=123).

I have no other option than javascript. I can't make this page php or aspx.

Kris
  • 13
  • 1
  • 3
  • See http://stackoverflow.com/questions/827368/use-the-get-paramater-of-the-url-in-javascript – Sampson Dec 16 '09 at 17:36
  • I don't think this should be closed. That question you linked to shows how to get the query strings, but it does not show how to append it to the `
    ` action.
    – Josh Stodola Dec 16 '09 at 17:40

2 Answers2

2
window.onload = function() {
  var frm = document.forms[0];
  frm.action = frm.action + location.search;
}
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
0

You can get access to the query string by location.search. Then you should be able to append it onto the form's action directly, something like the following:

// Get a reference to the form however, such as document.getElementById
var form = ...;

// Get the query string, stripping off the question mark (not strictly necessary
// as it gets added back on below but makes manipulation much easier)
var query = location.search.substring(1);

// Highly recommended that you validate parameters for sanity before blindly appending

// Now append them
var existingAction = form.getAttribute("action");
form.setAttribute("action", existingAction + '?' + query);

By the way, I've found that modifying the query string of the form's action directly can be hit-and-miss - I think in particular, IE will trim off any query if you're POSTing the results. (This was a while ago and I can't remember the exact combination of factors, but suffice to say it's not a great idea).

Thus you may want to do this by dynamically creating child elements of the <form> that are hidden inputs, to encode the desired name-value pairs from the query.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228