Skip to content

Lesson 3: Client side forms

James Cheney edited this page Jun 19, 2017 · 5 revisions
fun handleForm(s,i) {
  replaceNode(<div id="result">
      <p>The string was: {stringToXml(s)}</p>
      <p>The integer was: {intToXml(i)}</p>
      </div>,
      getNodeById("result"))
}

fun mainPage (_) {
  page 
    <html>
    <body>
      <h1>Example form, take 2</h1>
      <form l:onsubmit="{handleForm(s,stringToInt(i))}">
        A string: <input l:name="s" value="foo"/>
        An integer: <input l:name="i" value="42"/>
        <button type="submit">Submit!</button>
      </form>
      <div id="result" />
      </body>
    </html>
}


fun main () {
  addRoute("",mainPage);
  servePages()
}

main()

This example illustrates the second way to submit forms in Links. The form defined in the mainPage function is similar to the form in the previous lesson, but with one difference: the l:onsubmit attribute is used instead of l:action.

The difference between the two attributes is as follows:

  • l:action specifies a new page to display when the form is submitted. This is implemented via an HTTP POST request, involving a round-trip to the HTTP server that renders a new page. The action is specified by giving a Links expression that returns a page.
  • l:onsubmit specifies an action to take on the client when the form is submitted. This is implemented by JavaScript code running in the browser client, and does not necessarily involve a round-trip to the server (this can happen, though, if the action asynchronously contacts the server for some other reason). The action is specified by giving a Links expression that returns unit (); that is, the action may have side effects (such as modifying the DOM tree) but does not return a value or construct a new page.

Here, the Links code called when the form is submitted is handleForm(s,stringToInt(i)). Unlike the previous handleFomr function, this one does not construct a new page; instead it calls a function replaceNode that takes an XML fragment and a DOM node identifier. The latter is obtained by calling getNodeById("result") which finds the node in the DOM tree of the program that has id result. This node can be seen in mainPage; it is a <div> node that can be replaced with content showing the form result.

Exercises

  1. What happens if you change l:onsubmit to l:action?

  2. Modify the code to behave appropriately (e.g. showing an error message instead of the form results) if the value of the integer field is not a valid number. (Hint: Links supports regular expression matching e.g. str =~ /a*b*/ tests whether a string str is a sequence of zero or more as followed by zero or more bs).