Access URL Parameters with Javascript

I recently had to work on  a website where the user would submit a form and, if valid, be sent to a thank you page. I was asked to create a another form that redirected to the same thank you page and a new button on the thank you page that would allow the user to submit another set of data. The button would send the user back to the original form which would then repopulate a majority of the data for the user. The problem was the thank you page was a static HTML and I could not change it to a PHP script. JavaScript to the rescue!

First though, I modified the form page’s PHP to include the input values and form URL as parameters (aka search string or get variables) in the redirect URL. Then I added a form and submit button to the thank you page along with JavaScript that would add a hidden input to the form for every parameter and set the forms action to the URL parameter.

<form name="myform" method="post"><input type="submit" value="Submit"></form>	
<script type="text/javascript">
    window.onload = function() {
        var form = document.forms["myform"];
        window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            //create a hidden input element
            var element = document.createElement("input");
            element.setAttribute("type","hidden");
            element.setAttribute("name",key);
            //PHP encodes URI uses + for spaces instead of %20 so need to replace + with %20 before decoding
            element.setAttribute("value",decodeURIComponent(value.replace(/+/g,'%20')));
            form.appendChild(element);
        });
        //set form action to the url if there was none then send back to home
        form.action = ((form.url?form.url.value:'')||'./').replace(/^//,'');
    }
</script>

Of course I used a pretty image as the submit button instead of the ugly button.

The PHP page was already set to repopulate the form, using the $_POST variables,  if validation failed so this worked perfectly. Ideally the user wouldn’t be redirected but that was not my choice. Still, in a pinch, I think the JavaScript solution is quite proficient and flexible.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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