There are a number of ways to make the forms on your website more user friendly. This article will explain one way of doing this, which eliminates a page reload and replaces it with an image generated on the server.
Submitting a Form Using an Image Tag - Processing the Form (Page 3 of 8 )
As I mentioned, the getFormValues() function is used to retrieve the form values, validate them if necessary, and return a properly encoded query string containing the data from the form.
The first argument is the reference to the form that we had sent when the form was submitted. The second is a string value that is the name of a validation function that can be passed the value of each form control. How you implement validation is up to you, and will depend on the form values you are working with. In this example we pass this argument a value of null. If the name of a function is passed to this argument, the Javascript eval() function is used to pass each form value to the validation function.
We loop through all the form controls and determine whether the current form control is a text field. For larger forms with more types of elements (radio buttons, select menus, etc.), you could add additional type checks. Keep in mind that, since we will be using a GET request, this technique is best used with small forms that won't be transmitting a lot of data.
If the current element in the loop is a text field, we determine whether we have a validating function. If so, the values are sent to the function. Logically this validation function should prevent submission, and perhaps highlight the fields that need changing.
The eval() function works by taking the string passed to it and executing it as Javascript code. This is very useful for streamlining code and deciding which code to execute at runtime.
else
{
val = fobj.elements[i].value;
}
If there is no validation function specified, we simply store the value temporarily in the variable "val".
str += fobj.elements[i].name +
"=" + escape(val) + "&";
At the end of the loop, the name of the form element and the value is added to the query string, along with the "&" character to separate each name/value pair. The Javascript escape() function is used to replace any characters that are not valid in URLs with "%xx", with "xx" being the hexadecimal equivalent of the escaped character. An apace for instance would be "%20".
str = str.substr(0,(str.length - 1));
return str;
The loop will put an unnecessary "&" character at the end of the query string. Once the loop finishes assembling the query string, we clip the extra character off the end of the query string and return the completed string.