Code Sample

Capture Email Addresses from a Website

Use KVdb's bucket protection feature to collect emails from prospective users.

In this code sample, we will show you how to build an email capture form with HTML and use jQuery to save data into KVdb.

First, let's decide on a convention to use for keys and values. It would make most sense to use the email address as the key. A simple solution would be to use a boolean flag as the value, but we can do better than that. You might want to also record additional information, such as name and location for each email, so a more flexible approach would be to use a JSON object as the value. This way, you can store arbitrary data in the value, as well as the date and time. So let's define the following keys:

  • name: Full Name
  • created: Create Date (ISO 8601 format)

Create a new bucket protected by a secret_key so onle you will be able to get a list of emails.

$ curl -d 'secret_key=MY_SECRET_KEY' https://kvdb.io
Fd55uogXyxYdnXJvnyN8Xo

Next, let's create the HTML form:

Let's use jQuery and write a generic form submission handler that will collect all input fields inside the form and use their name attribute as the key inside the JSON object we will store in KVdb:

<script>
$('form').submit(function(e) {
  e.preventDefault();

  var value = {
    created: new Date().toISOString()
  };

  $(this).find("input").each(function() {
    value[$(this).attr("name")] = $(this).val();
  });

  if(value.email == "") return false;

  $.post("https://kvdb.io/Fd55uogXyxYdnXJvnyN8Xo/waitinglist_" + value.email, JSON.stringify(value))
    .done(function() {
      alert('Thank you');
    });

  return false;
});
</script>

Finally, to retrieve the list of emails and associated data, it's as simple as:

var regex = encodeURIComponent('^waitinglist_');
$.getJSON("https://kvdb.io/Fd55uogXyxYdnXJvnyN8Xo/?regex=" + regex + "&values=true&key=MY_SECRET_KEY", function(data) {
  data.forEach(function(row) {
    // row is an array with 2 elements: key, value
    var val = JSON.parse(row[1]);
    console.log("email: " + val.email + " name: " + val.name);
  });
});

As you can see, it's very easy to use KVdb to collect email addresses from prospective users, customers, or anyone else. The data is always available for export in JSON and other text formats so your data is always yours. While the above is just a simple example, it should help you get started.

For privacy reasons and regulatory requirements, it may not be possible to store personal information in KVdb in clear text. In these cases, encrypt (using public-key cryptography) both keys and values in the example above to pseudonymize any personal data. In the unlikely event of a data leak or misconfiguration in KVdb, the data stored in your bucket will be unintelligible to any attacker without the corresponding decryption key.

Check out other code samples at the documentation portal.