Submitting Forms: What Really Happens?


When a HTML form is submitted, a predictable sequence of events unfolds. This section is intended to demistify how the form data flows from the browser, to the server, into the CGI program and back again.


How it works:

1. A Web browser makes a request for a CGI-based service.
When a form is submitted, the values entered into the form are bundled together by the Web browser and a request is generated with this data attached. The request is sent to the URL designated by the form's ACTION attribute, which usually points to a CGI program located on the same server where the fill-out form originated.
2. The Web server takes the request and invokes the CGI program.
3. Encoded data is passed to the CGI program by the server.
Most CGI programs process form data and respond according to it. This data originates on the Web browser, which encodes it as a set of key/value pairs corresponding to the form's input fields and the values they have when the form is submitted.
key1=value1&key2=value2&key3=value3&key4=value4 ...

The encoding scheme is simple: equal signs separate names from their values, while ampersands separate each key/value pair; spaces are converted into plus signs, and special characters are changed into a hexidecimal notation. It is common for CGI programs to use separate program libraries to help decode this data.

4. The CGI program does its work.
Once the incoming data has been decoded, it's often used by the CGI program to trigger some external work, such as querying a database or sending a developer email.
5. Perhaps it writes some data.
6. Meanwhile, the browser waits...
This is correct. The connection between the Web browser making the original request and the server that invoked the CGI program is still alive. The browser idles as it waits to receive a response from the server. But the server has to wait too!
7. The CGI program generates a response.
Before the CGI program completes its work, it has to create a response that is in accord with the CGI standard. This consists of telling the server what sort of data the CGI program produces (followed by a blank line). Then it can output this data. Most CGI programs announce they will be creating a stream of HTML elements:
Content-type: text/html

It's a bit arcane, but that's what it looks like. After emitting this, the CGI program returns as much HTML as it likes and exits.

8. ...and the server sends the response to the browser.
Once the CGI program exits, the Web server takes the response returned by the CGI program and sends it along to the expecting Web browser. If the response is HTML, the Web browser displays the information. And this, at long last, is the result of the original form submission.