Class 8 – Persistent Data
Individual web pages are independent, standalone scripts that, by default, run independently of one another. But often on the web, especially on dynamic sites, you will want data to persist from one page to the next.
For example, when a user enters data into a login form on a page, you would expect the data they entered in the form to be available to the script (usually another file) that processes that form. Likewise, when a user logs in to a social network site, you would expect that user to stay logged in for all the other pages on the site. How does it do that if each page runs independently of each other?
Today, we cover three mechanisms available on the web for passing data from one page to another: forms, links, and cookies. You may see this process of passing data from one page to another referred to as “saving state”, “persistent data”, or “passing data”, regardless of which method is used.
Form data
Forms in XHTML are there for only one reason – to allow a user to enter some data on one page, and to then pass that data to another page. Form data is passed from one page to the next by attaching the data entered into the form onto the HTTP request for the next page.
This happens using one of the two ways the browser can request a page from a server: HTTP GET or HTTP POST. You can specify which method to use in the “method” attribute of the “form” XHTML tag.
The GET method passes data onto the query string of the URL specified in the “action” attribute of the “form” tag.
The POST method is similar to GET, but data is passed in a more discrete way that is invisible to the user.
Read more about HTTP GET and POST and passing data with forms.
Click to see an example using the GET method.
Click to see an example using the POST method.
Links
Since the data passed by a form using the GET method is simply tacked onto the end of the next page’s URL, it is possible to simulate a GET form submission using just a simple anchor tag.
Click to view an example of passing data using a link
Cookies
Last, but not least, you can save state between pages using cookies. Cookies allow data to persist for a customizable period of time until they expire. They are often used as part of user authentication and site usage tracking.
Here is an example of a page which sets a cookie
And here is a page which reads and outputs that same cookie
Combinations
Sites will often use a combination of the above methodologies. For example, you may want to pass information from one page to another using a form, and then store that information in a cookie so it is available to all other pages of the site.
Here is an example of passing data with a form and then storing it in a cookie
And this page reads that cookie and shows it to the user
Related posts:
Tags: class 8