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.
First let’s create our database table. In this case I am using mySQL:
My table is made up of only two fields:
- email – the actual email address of the user. Unique primary key and indexed for quick retrieval.
- 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:
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:
- Valid email & email is not already registered – add it to the database.
- Valid email & email is already registered – do nothing.
- 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.