Processing user submitted forms

Let's assume you want to give your customers an option to submit a form. Following submission form will be processed and a notification send to specified email address.

<form id="data" method="post" enctype="multipart/form-data" action="/apps/datajet/task/[your_task_id]">
  <input type="text" name="first" value=""> 
  <input type="text" name="last" value=""> 
  <input type="file" name="photo" > 
  <button>Submit</button>
</form>
<script>
  let form = document.querySelector("form#data");
  form.addEventListener("submit", function(event){
    event.preventDefault();
    fetch(form.action, {
        method: "POST",
        body: new FormData(form)
    })
    .then(response => response.json())
    .then(data => alert(JSON.stringify(data)))
  });
</script>

Above code creates a simple form with 2 text input fields and one file input field. This form is submitted via Ajax call to DataJet endpoint (please note task id is missing, replace it with your own task id).

Next, lets create a HTTP task with following code:

{% assign form_first_name = request.body.first | default: "" %}
{% assign form_last_name = request.body.last | default: "" %}

{% json upload_options %}
  {
    "fileName": "{{request.files.photo.name}}",
    "multipart": {{request.files.photo | default: "" | json }},
    "public": true
  }
{% endjson %}

{% assign result = upload_options | file %}

{% assign file_url = result.url %}

{% capture email_html %}
  <div>
    <h2> Hello! </h2>
    <p> You have new form submission from {{form_first_name}} {{form_last_name}} </p>
    <p> Following photo was attached: </p>
    <img src="{{file_url}}" width="500" height="600">
  </div>
{% endcapture %}

{% capture email_params %}
	{
        "to": "test@email.com",
        "subject": "New Form Submission",
        "replyTo": "test@email.com",
        "html": {{ email_html | json }}
  }
{% endcapture %}

{{ email_params | email }}

{% json res %}
    {
      "body": {
         "status": "ok"
      }
   }
{% endjson %}

{% assign response = res %}

This code:

  1. Accepts form submission

  2. Uploads attached file to your local storage

  3. Prepares html template for email

  4. Sends an email to address specified

Last updated