Category Archives: Code

Ajax Newsletter Subscribe Form

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="subscribe-submit.js"></script>
</head>
<body>
    <div id="mail-list">
        <form id="mail-list-form" action="subscribe.php" method="post">
            <span id="mail-list-instructions">Sign up to receive emails:</span>
            <input id="mail-list-email" name="email" type="text" maxlength="255" />
            <input id="mail-list-submit" type="submit" value="Add me" />
    </form>
    </div>
</body>
</html>

jQuery

$(document).ready(function(){
    $('form#mail-list-form').submit(function(event){
        var email = $('#mail-list-email').attr('value');
        var validEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (!validEmail.test(email)) {
            $('#mail-list-instructions').html('Please enter a valid email address:').css('color','red');
        } else {
            $.ajax({
                dataType: 'text',
                data: $(this).serialize(),
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                success: function(){
                    $('#mail-list').html('Thank you for your subscription, your address has been added to our list: '+email);
                },
                error: function(){
                    $('#mail-list').html('An error occured submitting the form data.').css('color','red');
                }
            });
        }
        event.preventDefault();
    });
});

PHP (SMTP with Pear Mail)

<?php
    require_once "Mail.php";
    $valid_referers = array(
        'http://example.com/', 
        'http://www.example.com/'
    );
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && in_array($_SERVER['HTTP_REFERER'], $valid_referers)){
        $subscriber_email = $_POST['email'];
        if ($subscriber_email <> '') {
            $headers = array (
                'To' => 'List Subscribe <info@example.com>',
                'From' => 'List Subscribe <webmaster@example.com>',
                'X-Mailer' => 'PHP/'.phpversion(),
                'Subject' => 'Mailing list add: '.$subscriber_email
             );
             $message = $headers['Subject'];
             $smtp = Mail::factory('smtp', array (
                 'host' => 'mail.example.com',
                 'auth' => TRUE,
                 'username' => 'example@example.com',
                 'password' => 'example'
             ));
             $mail_status = $smtp->send(
                 $headers['To'],
                 $headers,
                 $message
             );
             if (!PEAR::isError($mail_status)) {
                 include_once('thank_you.html'); // This is only displayed when the submit fails with AJAX
             } else {
                 header("HTTP/1.1 500 Internal Server Error");
                 echo $mail_status->getMessage();
             }
         } else {
             header("HTTP/1.1 400 Bad Request");
             echo 'Bad Request';
         }
     } else {
         header("HTTP/1.1 400 Bad Request");
         echo 'Bad Referrer';
     }
?>

Photo by Drew McLellan via Flickr used with CC Attribution, Non Commercial license