Session 15: HTML forms - myTeachingURJC/2018-19-PNE GitHub Wiki

  • Goals:
    • Learn how to create simple forms in HTML
    • Learn how to send information from the client to the server using the GET method
  • Duration: 2h
  • Date: Week 8: Tuesday, March-12th-2019
  • This session consist of the teacher's guidelines for driving the Lecture, following the learn by doing approach

Contents

Introduction

The clients can request resources from a web server, but also submit data to them. For sending information from the client to the server we use the html forms

Our first form

Let's create our first simple form: Just a text box with a submit button. We will use it to send a text message to our echo server. This is the HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>FORM 1</title>
  </head>
  <body>
    <form action="echo" method="get">
      Message to send to the server: <br>
      <input type="text" name="msg">
      <input type="submit" value="SEND">
    </form>
  </body>
</html>

If you open it in the browser you will see:

We have created two inputs. Each input is define with the <input> html tag. With the attribute type we define how is the input. The first one is a text input. The second one is a button for submitting the information

The text input has been named as msg. Also notice the action attribute on the form tag. Their value is "echo". This means that when the submit button is pressed, the client will emit a request message for the /echo resource

This is the request line generated by the client when the submit button is pressed, and we have typed the string "Testing..." into the text box

Happy web server

Let's write a web server that always response with the same page, regardless of what the client has requested (a happy server!). We want to test what happens when the submit button is pressed

  • Create a new folder called session-15
  • Create a new python file: form-server1.py, with the following code:
import http.server
import socketserver
import termcolor

# Define the Server's port
PORT = 8001


# Class with our Handler. It is a called derived from BaseHTTPRequestHandler
# It means that our class inheritates all his methods and properties
class TestHandler(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Print the request line
        termcolor.cprint(self.requestline, 'green')

        # Open the form1.html file
        f = open("form1.html", 'r')
        contents = f.read()

        # Generating the response message
        self.send_response(200)  # -- Status line: OK!

        # Define the content-type header:
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', len(str.encode(contents)))

        # The header is finished
        self.end_headers()

        # Send the response message
        self.wfile.write(str.encode(contents))

        return


# ------------------------
# - Server MAIN program
# ------------------------
# -- Set the new handler
Handler = TestHandler

# -- Open the socket server
with socketserver.TCPServer(("", PORT), Handler) as httpd:

    print("Serving at PORT", PORT)

    # -- Main loop: Attend the client. Whenever there is a new
    # -- clint, the handler is called
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("")
        print("Stoped by the user")
        httpd.server_close()

print("")
print("Server Stopped")
  • Write the previous html page in the form1.html file, in the session-15 folder
  • Run the server and try with the Browser

In the server's console notice the two request that have been generated by the client:

The first one is for requesting the main page (/):

GET / HTTP/1.1

The second one is for submitting the information from the client

GET /echo?msg=abcdef HTTP/1.1

Type of inputs

There are many different type of inputs elements you can use in your forms. In this HTML example you can see some of them:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>FORM 2</title>
  </head>
  <body>
    <h3>Example of different input elements</h3>

    <form action="myserver" method="get">
      Text input  <input type="text" name="msg">
      <br><br>
      Check button:
      <input type="checkbox" name="chk">
      <br><br>
      Radio buttons:
      <input type="radio" name="base" value="A" checked> A
      <input type="radio" name="base" value="C"> C
      <input type="radio" name="base" value="T"> T
      <input type="radio" name="base" value="G"> G
      <br><br>
      Options: <br>
      Choose operation:
      <select name="operation">
        <option value="count">Count</option>
        <option value="perc">Percentage</option>
      </select>
       <br>
        <input type="submit"/>
    </form>

  </body>
</html>

This is how the looks like in the browser:

In this animated gif you can see how the work:

Exercises

The only way of learning is practicing...

Exercise 1: Echo Server

Develop an Echo Server with forms. When you ask the server for the main page (/ resource) it should return a form with a text input and a submit button. When a text message is sent to the echo server, it will generate a response html page that contains the user message. With a link in the bottom it should be possible to return to the main form. The message will be processed though the echo action

If the requested resource is different form / or /echo, the server will return an error page, with a link in the bottom for returning to the form

Exercise 2: Echo server with check button

Modify the echo server for including a check button. When it is checked, the echo should be converted into capital letters

Authors

Credits

  • Alvaro del Castillo. He designed and created the original content of this subject. Thanks a lot :-)

License

Links

⚠️ **GitHub.com Fallback** ⚠️