ChatiumFor developersPlaygroundPricing
Sign in

Processing the Form

So, we have a form, but it doesn't do anything yet. Let's add a handler for this form.

Let's add a handler at the bottom of our file that simply returns what the form sends to it.

const addRoute = app.post('/add', async(ctx, req) => {
  return req.body;
});

We defined a route with the address plugin/index~add. If a POST request is sent to it, it will simply return what was sent.

Now, let's direct our form to this address by setting the method='post' property in our <form> tag and specifying the action attribute to point to this route, using curly braces because we will substitute a variable into it.

<form method='post' action={addRoute.url()}>

Additionally, let's add the required and type='number' properties to our Input tags so that the browser...

The code we should end up with looks like this:

import {jsx} from '@app/html-jsx';
import {PluginLayout} from '@html/layout';
import {Container, FormRow, Input, Button} from '@html/ui';

const mainPage = app.html('/', async(ctx, req) => {
  return <PluginLayout ctx={ctx}>
    <Container padding='xl' width='sm'>
      <h1>BMI Chart</h1>
      <form method='post' action={addRoute.url()}>
        <FormRow label='Height' description='in centimeters'>
          <Input type='number' name='height' required />
        </FormRow>
        <FormRow label='Weight' description='in kilograms'>
          <Input type='number' name='weight' required />
        </FormRow>
        <FormRow>
          <Button type='submit' primary>Add Entry</Button>
        </FormRow>
      </form>
    </Container>
  </PluginLayout>;
});

const addRoute = app.post('/add', async(ctx, req) => {
  return req.body;
});

Let's enter our height and weight, click the "Submit" button, and see what the result looks like.

We can see that the data from the form arrived in req.body. We have the user's height and weight; let's calculate the Body Mass Index (BMI) and display it.

const addRoute = app.post('/add', async(ctx, req) => {
  // height in meters
  const height = Number.parseFloat(req.body.height) / 100;
  // weight in kilograms
  const weight = Number.parseFloat(req.body.weight);
  // calculate BMI using the formula
  const bmi = weight / (height * height);   
  
  // return the result
  return {
    bmi: bmi 
  };
});

Now let's submit the form again and see what the script outputs.

So, we calculated the Body Mass Index based on the submitted form. In the next lesson, we will learn how to record everything that the user sent us into a table.

Next Lesson: Adding Entries to the Table