Fragmented Thought

Post from Form inside Form

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

I've got a mass edit form for orders on one of the sites I work on. Each order needed link or button to track the shipments of that order using UPS. Well, today we added FedEx tracking as well. UPS was easy, they do everything via url, so a simple link worked fine. FedEx, not so much, you have to post everything over to them. Obviously that creates a sort of form within a form, and that's not valid html. Javascript becomes required, here's your setup:

<form> <input name="asdf" value="1" /> <p>Tracking button goes below this paragraph</p> <button type="button" onclick="post_to_url( 'http://fedex.com/Tracking' ,{ 'ascend_header':'1' ,'clienttype':'null' ,'mi':'n' ,'track':'y' ,'cntry_code':'null' ,'language':'null' ,'tracknumbers':'#FedExTrackingNumber#' ,'action':'1' } ,'_blank' )" > Track </button> </form>

And the generic javascript function you need:

function post_to_url(path, params, target, method) { target = target || ""; // Set method to post by default, if not specified. method = method || "post"; // Set method to post by default, if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); form.setAttribute("target", target); for (var key in params) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } document.body.appendChild(form); // Needed for only some browsers form.submit(); }