I’ve implemented similar functionality on numerous sites by now, and I thought I would write up a short post on how to do this using jQuery and ColdFusion. The goal is to create a simple form text input which will collect someone’s email and add it to a database table. Basic stuff, with just a touch of jQuery to make all of this happen using AJAX.

Database table

First let’s create our database table. In this case I am using mySQL:

My table is made up of only two fields:

  1. email – the actual email address of the user. Unique primary key and indexed for quick retrieval.
  2. date_subscribed – timestamp reference of when each email is added.

Client side code

Next up we write up a basic HTML form with an input box and a submit button that will look like this:
Subscribe Form

Eventually of course, you will position and style this form to fit your design. For now, we will use some CSS to spice it up a bit, and hide the message box area by default – this is the area that will display our AJAX messages returned from the server and will be made visible using JavaScript only when a message comes in. Finally, we bind the click event of the form’s submit button to submit the AJAX call.

Here’s our form’s HTML:

The accompanying CSS:

And the jQuery code:

There are plenty of inline comments above which make the code self-explanatory. The server side page that gets called through AJAX is one I named ajax.cfm, passing it an action and a value (the email to add).

Server side code

The ColdFusion code basically handles 3 scenarios and returns the corresponding messages back to the client:

  1. Valid email & email is not already registered – add it to the database.
  2. Valid email & email is already registered – do nothing.
  3. Invalid email – do nothing.

Just make sure to edit your database connection for the queries – the APPLICATION.dsn in the code. And that’s really it. Feel free to play around with this sample and let me know if you have any questions or know how to improve it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.