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.

Replay

Category: javascript Time: 2006-11-01 Views: 3
Tags:

Related post

  • Insert values in database from array table using ajax and php 2016-01-23

    help me to insert data from array inputs from my table using ajax and php. I have the separate php file, but it is blank at the moment. this is my current html + php code: <form class='form-horizontal form-validate' id="form"> <?php ech

  • Using Ajax and PHP to update shopping cart 2016-02-17

    I am attemtping to use Ajax and PHP to create a shopping cart. At the moment I console.log and can see that the correct product ID is being selected when I click 'add cart' but nothing happens in my PHP when I try and var dump the POST data that shou

  • Using Ajax and PHP to insert and update page without reloading 2016-01-21

    This question already has an answer here: How to avoid page reload in php form submission 3 answers I am new to Ajax and have just started using PHP and I have made this working using PHP but it reloads the page, as one expects. When I press a button

  • display text using ajax and php 2016-02-05

    I'm just trying to do a simple thing in ajax but it does not work. I just want to display a text when i click on the input button ajax.js jQuery(document).ready(function($) { $('#insertForm').change(function(){ //on recupere la valeur de l'attribut v

  • How to upload imageDataBase64 using ajax and php? 2016-03-02

    currently i developing a mobile apps that can snap and upload photo to my database. Now i able to snap photo and pass the imageDataBase64 to php using ajax but dunno why when the data pass to my ajax, it show the error message on the ajax. I dunno wh

  • Updating mysql records using ajax and php result is null 2016-02-15

    i'm trying to update records in a form using php and ajax. My ajax response is {"result":null,"errors":false} I have double-checked to make sure my column names match up and everything but I can't figure out what is wrong. The data doe

  • Using AJAX and PHP to load next post object 2014-07-16

    After looking through the jQuery documentation and many stackexchange community forums, I am still faced with this problem. Taking little bits from here and there have helped me get this far, but I am stuck where I am now. Im using an ajax request to

  • How to fetch data from multiple tables in live search using ajax and php 2016-01-17

    I know that this kind of questions have been asked and answered but my problem is little bit different. I have two tables named category and enterprises. Onkeyup I want to show records from both tables,matching that string which is entered in search

  • How do I enable CORS in an online server using AJAX and PHP to get font for use on another BigCartel site 2016-01-18

    I am currently using BigCartel to design a website. I wish to use a custom font. No matter which server I use (currently a free Hostinger server) I cannot enable CORS using htaccess. Added to .htaccess: # Header always add Access-Control-Allow-Origin

  • Using AJAX and PHP for a pop up? 2016-02-02

    I have a page using HTML 5 drag and drop elements. When dropped into a container (div) it calls an ajax function function drop(containerId, e) { var id = event.dataTransfer.getData("id"); console.log(id); $.ajax({ url: "dataworker.php"

  • Not updating session variables correctly using ajax and php 2016-02-15

    I have a problem with session variables update. I wrote a simple site to explain it. First of all, is this the right way to deal with this issue of getting inputs from divs already updated with ajax? If so, is there any way to make sure the session v

  • how to asynchronously get data using ajax and php 2016-01-23

    i am new in ajax. i want to display the text entered inside the input to another div element.here is the image given below: here is my code : <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery

  • How to delete grand grandparent using jQurery, AJAX and PHP 2016-06-12

    I am using bootstrap. I want to delete specific row in the database using AJAX and PHP. I have inserted BOOTSTRAP PANEL inside a .col-md-6. I have inserted delete button inside .panel-footer. Column id is dynamically generated by PHP and MySQL. Pleas

  • Upload Image to database using Jquery ajax and PHP 2016-02-14

    Hello guys hope you can help me with this, becuase i have no idea... I want to upload an image into a database table i just need to upload the image, and some other data, right now i save all the info in the data base using the following Code: $.ajax

  • Is there a way to use Java and PHP on the same Apache server or at least, same port? 2011-10-07

    I am pretty new to Java for Web and my question is if I can use Java and PHP together? I know I can use them together, let's rephrase the question, is there a way to access them at the same port? Java uses Tomcat, can PHP use tomcat also? -----------

  • error when using nginx and php-cgi on Windows: No input file specified 2012-04-29

    I get the above error when using nginx and php-cgi on Windows. This is my nginx configuration: worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65

  • How to solve SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in ajax and php 2016-02-06

    How to solve this error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data i was sending some data from and to ajax and php. here is my ajax code: flag = 111; var dt = $(this).serializeArray(); dt.push({name: 'flag', v

  • how to fetch data using json and php 2016-07-04

    How to fetch json result using mysql connection $conn = new mysqli("localhost", 'root', "", "laravel"); $query = mysqli_query($conn,"select * from customers"); while($result2=mysqli_fetch_assoc($query)) { echo "

  • How to upload file using ajax and file extension validation using ajax in freeform? 2013-11-27

    I'm using Freeform 4.0.11. I have a form, which i want to upload file using ajax and also check file extension validation using ajax. Except file upload field, every fields value are submitted, but i can't got attachment file. So, How i can upload my

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 4.876 (s). 13 q(s)