#native_company# #native_desc#
#native_cta#

Use jQuery to Build Newsletter Subscription Popup with a MySQL/PHP Backend Page 2

By W. Jason Gilmore
on January 19, 2011

Expiring the Modal Using a Cookie

When the visitor closes the window, either by want of disregarding the message or after subscribing to the newsletter, it’s important to ensure the window doesn’t again appear following the next request (even a page reload request). To prevent subsequent modal windows from appearing for a designated period of time, we’ll set a cookie after closing the window and then check whether that cookie exists with each request. The jquery-cookie plugin makes this a trivial matter. Begin by downloading the plugin and then referencing it within your website like this:
<script src="jquery.cookie.js" type="text/javascript"><!--mce:4--></script>
Next, revise the embedded JavaScript, encapsulating the call to SimpleModal’s modal() method within an IF statement which uses jquery-cookie to determine whether a cookie named newsletter exists and has been set to 1. If not, the modal window will be displayed. Once the visitor closes the window, jquery-cookie will create the cookie and set its expiration date for seven days into the future. The revised JavaScript code looks like this:
$(document).ready(function () {

  if ($.cookie("newsletter") != 1) {
    $('#basic-modal-content').modal({
      onClose: function() { 
        $.cookie("newsletter", "1", { expires: 7 }); 
        $.modal.close(); 
      }
    });
  }

});
As a reminder, be sure to set the cookie expiration date far enough into the future so the visitor will not become annoyed by the modal dialog. Additionally, when using modal dialogs for features such as a newsletter subscription prompt, consider setting a different cookie following the window’s closure which sets a cookie which never expires, just to make sure the user doesn’t attempt to again subscribe to the newsletter.

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.