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:
CREATE TABLE 'subscriber' ( 'email' varchar(250) NOT NULL, 'date_subscribed' timestamp NULL DEFAULT NULL, PRIMARY KEY ('email'), UNIQUE KEY 'subscriber_main_index' ('email') )
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:
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:
<form id="frmSubscriber"> <fieldset> <input id="subscriber-value" name="email" type="text" /> <input id="subscriber-add" type="submit" value="Subscribe" /></fieldset> </form>
The accompanying CSS:
#frmSubscriber fieldset div#subscriber-message { background-color: #F1F1F1; border: 1px solid #999999; border-radius: 10px; color: #666666; display: none; font-size: 14px; margin: 5px 0 15px 0; padding: 5px; } #frmSubscriber span.subscriber-error{ color: #FF0000; }
And the jQuery code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script> <script language="JavaScript"> // Subscriber fields var objSubscriberValue = $( '#subscriber-value' ); var objSubscriberAdd = $( '#subscriber-add' ); var objSubscriberMessage = $( '#subscriber-message' ); // We bind the form's submit button click event. objSubscriberAdd.bind( 'click', function( event ) { // Proceed only if something was typed in the email input field. if( objSubscriberValue.val().length > 0 ) { // Make sure the message box is invisible // since this is a new request. objSubscriberMessage.hide(); // Make the AJAX request. $.ajax({ url: '/ajax.cfm', data: { action: 'subscriber-add', value: objSubscriberValue.val() }, type: 'post', context: document.body, // In case of an error display a prompt. error: function( jqXHR, textStatus, errorThrown ){ alert( 'There was a critical error communicating with the server' ); }, // Successful request. success: function( data, textStatus, jqXHR ) { // Add HTML result in our form's message box. objSubscriberMessage.html( data ); // Make the message box visible. objSubscriberMessage.show(); } }); } // Prevent the default action. event.preventDefault(); }); </script>
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
<cfsetting enablecfoutputonly="true" /> <!--- Define page variables. ---> <cfparam name="FORM.action" type="string" default="" /> <cfparam name="FORM.value" type="string" default="" /> <cfparam name="VARIABLES.qResults" type="query" default="#queryNew('')#" /> <cfset FORM.action = trim( FORM.action ) /> <cfset FORM.value = trim( FORM.value ) /> <!--- Pick an action to perform. ---> <cfswitch expression="#FORM.action#"> <cfcase value="subscriber-add"> <!--- BEGIN: Something was passed in as an email. ---> <cfif len( FORM.value )> <!--- Only proceed if the value is a valid email address. ---> <cfif isValid( "email", FORM.value )> <!--- See if the email is already registered. ---> <cfquery name="VARIABLES.qResults" datasource="#APPLICATION.dsn#"> SELECT email FROM subscriber WHERE email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#FORM.value#" /> </cfquery> <!--- Email is already registered. ---> <cfif variables.qResults.recordCount> <cfoutput> <span class="subscriber-error"> This email address is already registered. </span> </cfoutput> <!--- This is a new email. ---> <cfelse> <!--- Save it in the database. ---> <cfquery datasource="#APPLICATION.dsn#"> INSERT INTO subscriber ( email ,date_subscribed ) VALUES ( <cfqueryparam cfsqltype="cf_sql_varchar" value="#FORM.value#" /> ,<cfqueryparam cfsqltype="cf_sql_timestamp" value="#now()#" /> ) </cfquery> <!--- Message to be returned to the user. ---> <cfoutput> Thank you!<br /> You've been added to our newsletter. </cfoutput> </cfif> <!--- Not a valid email address. ---> <cfelse> <cfoutput> <span class="subscriber-error"> Sorry!<br /> This is not a valid Email address. </span> </cfoutput> </cfif> </cfif> <!--- END: Something was passed in as an email. ---> </cfcase> </cfswitch> <cfsetting enablecfoutputonly="false" />
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.
[…] Read the rest here: Using jQuery and ColdFusion to collect emails | Evagoras Charalambous […]