Forum Moderators: open

Message Too Old, No Replies

how to obtain URL generated by GET submit, on the client side

         

mfunke

4:27 pm on Dec 2, 2004 (gmt 0)



I have a FORM with method=GET. I'd like to obtain the URL that will be generated by the submit operation. But I want to get this URL _before_ it is submitted (e.g I don't want to make an HTTP request and have some CGI program echo it back).

Is there an easy way to get this information using Javascript on the client side?

thanks, mark

DrDoc

1:23 am on Dec 3, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld! [WebmasterWorld.com]

Interesting... Well, I guess it's possible, but a little bit tricky. You'd have to iterate through the form elements, check the data, do any URL encoding (if applicable), and thereby build the query string. As long as you don't have an image as the submit button you'd be able to build the exact query string. With an image, you'd get everything except for the x and y coordinates of the mouse click.

Otherwise, the easiest way (if you're only doing this for testing purposes, thus not in a live environment) would be to submit the form to a simple HTML page where you simply do something like:

document.write(location.search);

rocknbil

3:57 am on Dec 3, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



would this work? I've only done the select list and text/textarea objects, you'd have to add some things for radios and such . . .

<form method="get" action="foo.cgi">
<INPUT TYPE="text" NAME="field1"><br>
<INPUT TYPE="text" NAME="field2"><br>
<INPUT TYPE="text" NAME="field2"><br>
<select name="field4">
<option value="green widgets">green widgets</option>
<option value="blue widgets">blue widgets</option>
<option value="red widgets">red widgets</option>
</select>

<input type="button" onclick="buildURL(this.form)" value="Send it">
</form>

<script language="Javascript">

function buildURL(form) {
var str,fld,val = '';
var sendIt=false;
str = 'http://foo.cgi?';

for (i=0;i<form.elements.length;i++) {
var obj = form.elements[i];
fld = escape(obj.name); //in case you use special characters
if (obj.type=='select-one') {
val = obj.options[obj.selectedIndex].value;
}
else { val = obj.value; }
if (val!= '') {
val = escape(val);
str += obj.name+'='+val;
if (i< (form.elements.length-1)) { str += '&'; }
}
}
sendIt = confirm('OK to send " ' + str + ' "?');
if (sendIt == true) { form.submit(); } // or document.location=str, since it's get
else { alert('URL string " ' + str + ' " cancelled.'); }
}

</script>