Wednesday, November 12, 2008

Sometimes you want a GET and a POST - Javascript Howto

There may be a time you prefer something to submit via POST, but want to make the variables bookmarkable for easy reference. (One reason to do this is if uploading a file. Obviously you can't hold the file in a get variable but all of the options concerning the upload can be held in this fashion.) This is a cheap easy way to do that:

Remember to put the code block under the form declaration, or the last time won't work.


<script type="text/javascript">
function concatenateFields() {
concatenateFields = '';
for(i=0;i<document.forms[0].length;i++) {
concatenateFields += document.forms[0].elements[i].name + '=' + document.forms[0].elements[i].value + "&" ;
}
return concatenateFields;
}
function changeAction(){
actionfile = 'try.php?';
document.forms[0].action = actionfile + concatenateFields();
alert(document.forms[0].action);
return false;
}

document.forms[0].onsubmit = changeAction
</script>

No comments: