Use AJAX and PHP to Build your Mailing List

An elegantly designed site filled with engaging content is worth very little without an interested audience. An opt-in mailing list is one of the most effective methods of making contact with your audience and driving repeat traffic to your site. If visitors enjoy and trust your site, they’re likely to trust you with their email addresses — after all, they’ll want to be informed of new products, articles, or other relevant information. This is a great way to build relationships with your site’s users, and encourage them to come back to your site again and again.

In this article, we’ll learn to use AJAX to accept subscriptions to your mailing list without having to refresh the page; with this approach, your signup process will be quick and painless. Our AJAX sign up form will also be able to accept subscriptions from visitors who don’t use modern, AJAX-capable browsers.

This article assumes that your mailing list is stored in a MySQL database, but as long as you have the necessary code to add addresses to your own mailing list, it should be easy for you to adapt the code presented in this article to your own signup process.

Before we get started, download the code, and take a look at what we’ll cover in this tutorial.

The Big Picture

Our mailing list signup system has three key components:

  1. An HTML form inside a PHP page receives the visitor’s email address.
  2. JavaScript will listen for the form submission, which will trigger the AJAX call to the server with the email address.
  3. A simple PHP page on the server will receive the address. It will check the email address for errors, then store the address in a MySQL database. A success or error message will be sent back to the HTML page for user feedback.

We’ll also ensure that this signup functionality is accessible to all, by writing a PHP-based sign up for users who don’t have JavaScript enabled in their browsers.

To simplify the AJAX coding in our system, we’ll use the popular JavaScript library Prototype to listen for form submission, and to handle the AJAX messages. If you need a primer on Prototype, check out Dan Webb’s articles Painless JavaScript Using Prototype and The JavaScript Library World Cup.

Form Proceeds Function

Our first step is to build the form that will receive the email address; then, we’ll connect to the JavaScript files to deliver the functionality. Here’s what the form looks like:

<form id="addressForm" action="index.php" method="get"> 
 <fieldset>
   <legend>Join our mailing list!</legend>
   <p>
     <input type="text" name="address" id="address" />
     <input type="submit" value="Sign Up" />
   </p>
   <p id="response"><?php echo(storeAddress()); ?></p>
 </fieldset>
</form>

The form itself is quite simple. We simply have a text field to accept the user’s email address, and a submit button to trigger the AJAX functionality. The ID of the form will be critical, as it will allow for our JavaScript to listen for a submission.

Notice in the form the paragraph that contains the output of a PHP function called storeAddress? This is the heart of our accessible signup form. When the page is loaded for the first time, storeAddress returns a single non-breaking space so that the paragraph appears empty. Later, when our AJAX functionality is triggered by the user’s submission of an email address, JavaScript will insert a message into this paragraph to let the user know what’s going on. Alternatively, if the user doesn’t have JavaScript enabled in the browser, the form will be submitted, which will cause this page to be loaded again. This action will cause storeAddress to be executed again. And this time, it will return a message for display inside the paragraph.

In the head of the page, we’ll link to the Prototype library with a <script> tag. We’ll also link to mailingList.js, which we’ll look at next:

<script type="text/javascript" src="js/prototype.js"></script> 
<script type="text/javascript" src="js/mailingList.js"></script>

The beauty of this setup is that structure of the page is totally isolated from its functionality, which makes development and maintenance hassle-free.

Using AJAX to Deliver the Address

Inside the js folder, alongside the prototype.js file, is a file called mailingList.js. This file contains the code that drives the AJAX functionality specific to this page. Our first item of business in this file is to add an event listener to the form element’s submit event, which will trigger the AJAX call to the server. However, we can’t do this straight away — we need to wait until the page is loaded, which is signified by the window object’s load event.

To add these event listeners, we’ll use Prototype’s convenient observe method. We first add a listener for the page’s load event. Inside this listener, we attach an event listener to our form’s submit event:

// Attach handler to window load event 
Event.observe(window, 'load', init, false);

function init() {
 // Attach handler to form's submit event
 Event.observe('addressForm', 'submit', storeAddress);
}

Notice that the event listener for our form will call the JavaScript function storeAddress when the form is submitted. This storeAddress function contains the JavaScript to make an AJAX call to our PHP script. Here’s what it looks like:

function storeAddress(e) { 
 // Update user interface
 $('response').innerHTML = 'Adding email address...';
 // Prepare query string and send AJAX request
 var pars = 'address=' + escape($F('address'));
 var myAjax = new Ajax.Updater('response', 'ajaxServer.php', {method: 'get', parameters: pars});
 // Stop form from submitting when JavaScript is enabled
 Event.stop(e);
}

This function is very simple. It starts by letting the user that something’s going on by displaying an "Adding email address…" message. Next, we collect the information from the form in preparation for sending an AJAX request. Notice how we access the contents of the text field using Prototype’s $F function, which grabs the value of a given form element when supplied with that form element’s ID. We use the JavaScript escape function to convert the user input to Unicode format; this way, its URL is ready for delivery to the PHP script via the GET method.

Then comes the most important part of this function: the creation of a new Ajax.Updater object. When we create an Ajax.Updater object, we pass it some parameters, including:

  1. the ID of the element in which you want to show the response from the server
  2. the URL of the PHP script
  3. the data you want to send to the server-side script, and the method of delivery (i.e. POST or GET)

The Ajax.Updater will send the email address to the server and wait patiently for a response. When it receives a response, it will display it in place of the "Adding email address…" message we inserted at the start of the method. Finally, we call Event.stop (another function supplied by the Prototype library) to stop the form from actually being submitted to the server.

Set Up your Mailing List Database

Before we can write any PHP to store email addresses, we need a place to put them. This SQL will build a table named mailinglist for you:

CREATE TABLE `mailinglist` ( 
 `id` INT NOT NULL AUTO_INCREMENT ,
 `email` TEXT NOT NULL ,
 PRIMARY KEY ( `id` )
);

Included in the code archive is a PHP file called createTable.php, which will create this table for you. However, before you run this file, you’ll need to update the dbConstants.php file with the details of your MySQL database. I suggest you update this file now, as we’ll be using these constants in the next section.

Storing the Email Address

We’ve set everything up to deliver the address to the server; now PHP will finish up the process by storing the address in your database and returning a string to our Ajax object to indicate success or failure. Let’s take a look at the ajaxServer.php file to which the email address is sent.

<?php 
require_once("inc/storeAddress.php");
echo(storeAddress());
?>

This very simple PHP script calls a function called storeAddress and returns to the Ajax object the message that’s returned by storeAddress. Communicating with the Ajax object is as simple as printing a string.

The first thing storeAddress does is initialize a variable called $message to a non-breaking space. Then, it makes sure the script has received an email address in the query string. If it hasn’t, we’ll leave $message variable set as a non-breaking space. $message will be returned to the caller at the end of this function.

function storeAddress() { 
 $message = "&nbsp;";
 // Check for an email address in the query string
 if( !isset($_GET['address']) ){
   // No email address provided
 }

Once we are certain we have an email address to work with, we’ll want to make sure it’s a valid address. We’ll use a regular expression to look for some alphanumeric characters followed by the @ symbol, more alphanumeric characters, a period, and some more alphanumeric characters. If this test fails, we’ll set $message to an error message, informing the user that the entered email address was invalid:

  else { 
   // Get email address from the query string
   $address = $_GET['address'];
   // Validate Address
   if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@
   [a-z0-9-]+(.[a-z0-9-]+)*$/i", $address)) {
     $message = "<strong>Error</strong>: An invalid email address was provided.";
   }

If the address passes this test, we’ll store it in the database. To do this, we connect to MySQL, select the database, and run our INSERT query. If the address was stored properly, we set $message to a success message; otherwise, we set $message to an error message.

    else { 
     // Connect to database
     $con = mysql_connect(DBHOST ,DBUSER, DBPASS);
     mysql_select_db(DBNAME, $con);
     // Insert email address into mailinglist table  
     $result = mysql_query("INSERT INTO mailinglist SET email='" . $address . "'");
     if(mysql_error()){
       $message = "<strong>Error</strong>: There was an error storing your email address.";
     }
     else {
       $message = "Thanks for signing up!";
     }
   }

Finally, we return $message to ajaxServer.php:

  }   return $message; }

Now, load the page, enter your email address, and submit the form — you should see your email address added to the mailinglist table without the page reloading. Even if you disable JavaScript, the page will work in a very similar fashion, except that instead of inserting the output of storeAddress into the page dynamically using JavaScript, it’s inserted directly into the HTML in the page’s PHP code.

AJAX really makes signing up for your mailing list a piece of cake. There’s no waiting for the page to reload, which interrupts your visitor’s browsing experience, and there’s no need to exclude those who browse with JavaScript disabled. Prototype makes the process of building AJAX functionality quick and painless, allowing you to keep in close touch with your site’s fans.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.findferry.co.uk Ferry

    That was a smart way of doing it Aarron.

    Thaks for sharing :-)

  • http://www.otreva.com Mike

    I just used this tutorial except I changed the script to use PHP’s sendmail instead of storing in a database.

    Thanks for sharing.

  • http://blog.web-design-site.ro/ Seoweb Seco

    looks great … but if I send 5 times … 5 times is recorded in the database.
    If this problem is solved .. I think it is the nicest way to implement this form

  • Mihkel

    Thanks for the tutorial, saved my life. Wish you well.