Learn How To Create An AJAX PHP Coming Soon Page

In this tutorial we are going to learn how to create a Coming Soon Page which allows the visitor to send their email address which can be delivered to an email or to be stored in a database. This will just a similar approach to a contact form but then a setting will decide how the email address is stored.

If you expect there to be many sign ups it's normally easier to directly store these email addresses to a database so you can email them with updates later.

This page will also allow you to send an email to an admin account to send the visitors email address.

To make it easier for the visitor this page will use JQuery and the AJAX function to send the visitors email address. This means that the page won't need to be refreshed to send the email address to the server.

Coming Soon Page HTML

The HTML needs to have the website logo for branding, keywords used on the site, a brief paragraph explaining what is intended by the website and links to your social networking profile pages.

The most important thing to have on a coming soon page is a form to collect emails. In this tutorial we are going to be working with a basic HTML layout as this is about processing the email collection form.

As you can see this is a very simple page with a H1, paragraph tag, social links and a textbox and a button.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> 
<link rel="stylesheet" href="style.css" type="text/css" title=""> 
</head>
<body>

<div id="container">

	<h1>Website Coming Soon!</h1>
	
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, massa et mollis bibendum, orci mi venenatis velit, 
	sed convallis arcu massa sed nulla.</p>
	
	<h2>Keep Updated</h2>
	
	<a href="http://www.twitter.com/paulund_" target="_blank"><img src="images/icons/twitter_32.png" title="Twitter Profile" alt="Twitter Profile" /></a>
	<a href=""><img src="images/icons/facebook_32.png" title="Facebook Profile" alt="Facebook Profile" /></a>
	<a href=""><img src="images/icons/linkedin_32.png" title="Linkedin Profile" alt="Linkedin Profile" /></a>


	<div id="email_form">
		<div id="form_status">
			<h4></h4>
			<p></p>
		</div>
		
		<input type="text" id="email" value="enter your email address to stay updated..." />
		<input type="button" id="submit" value="Submit" />
	</div>
	
</div>
<script src="script.js" type="text/javascript"></script> 
</body>
</html>

Coming Soon Page JQuery

The JQuery on this page will take care of submitting the email to the server. We will use the built-in function to use AJAX to submit the email to the server.

JQuery makes it very easy to use AJAX to submit data back to server. AJAX allows you to make a round trip to the server without refreshing the page, on the response back from the server we will display a message depending on the result from the server.

Document Ready Function

/**
 * Document ready will run after the page elements have loaded
 */
$(document).ready(function(){
	//Empty the email textbox when the user clicks on the textbox
	$("#email").focus(function () {		
        $(this).val('');
   });
	
	//Click Event on the submit button
	$("#submit").click(function () {
		//Convert the email to lowercase
		var email = $("#email").val().toLowerCase();

		//If email is empty display an error
		if(email == ''){
			emailStatus("error");
		} else {
			//If email isnt empty then validate the email
			if(!validateEmail(email)){
				//If email hasn't validated then display error message
				emailStatus("error", "Email is not valid");
			} else {
				//If email is valid then submit the email passing through the valid email address
				submitEmail(email);
			}			
		}
   });
});

Validate Email Address

/**
 * Validate email function with regualr expression
 * 
 * If email isn't valid then return false
 * 
 * @param email
 * @return
 */
function validateEmail(email){
	var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	var valid = emailReg.test(email);

	if(!valid) {
        return false;
    } else {
    	return true;
    }
}

Submit Email Address Using jQuery AJAX

/**
 * If the email validates then send the email address to the server to be processed
 * 
 * @param email
 * 
 * 
 * @return
 */
function submitEmail(email){
	//jQuery ajax request to process page
	$.ajax({  
		  type: "POST",  
		  url: "./process.php",  
		  data: 'email=' + email,  
		  success: function(result,status) { 
			//email sent successfully displays a success message
			if(result != 'failed'){
				emailStatus("success");
			} else {
				//email failed display message
				emailStatus("error", "Email was not sent please try again");
			}
		  },
		  error: function(result,status){
			  //Ajax returns error display error message
			  emailStatus("error", "Email was not sent please try again");
		  }  
		});  

	return false;
}

Display Email Contact Status

/**
 * This is a function which will display the status message to the user
 * 
 * @param status
 * To display a error or a success status
 * 
 * @param message
 * The message to display to the user
 * 
 * @return
 */
function emailStatus(status, message){
	
	//decide what status to display the user default is an error
	switch(status){
		case "error":
		default:
			//Clear all classes and add a error class
			$('#form_status').removeClass().addClass('error');
		
			//Add error heading
			$('#form_status h4').text('Error');
			
			//Add message to error status
			if(message == undefined){
				$('#form_status p').text('Please enter an email address.');
			} else {
				$('#form_status p').text(message);
			}
			
		break;

		case "success":
			//Clear all classes and add a success class
			$('#form_status').removeClass().addClass('success');
			
			//Add success heading
			$('#form_status h4').text('Success');
			
			//Add message to success status
			if(message == undefined){
				$('#form_status p').text('Email has been sent successfully.');
			} else {
				$('#form_status p').text(message);
			}
			
		break;
	}
}

 

PHP Store Email Or Send Email

There is a setting on the contact script which will allow you to change from sending the email in a HTML email to an admin address, or to submit the email to a database to store on a table. The best solution if you are expecting a large audience is to store the emails in a database, so that you can use this list to send out email updates to the visitors.

Create Email Process Class

This will create your email class and will store your visitors email in a database when it is sent to the server.

&lt;?php

$process = new process_coming_soon();

//Set the registering email
$process->from_email = $_POST['email'];
$process->to = "Your email address here";
$process->process();

class process_coming_soon {
	
	private $form_type = false; 	//Email or store user email
	private $to = false;
	
	public $from_email = false;
	
	/**
	 * Class Constructor
	 */
	public function __construct(){
		//Pick email or store in lowercase
		$this->form_type = 'store';
	}
}
?&gt;

Process The Email Form

If the form type is store the email will be stored in the database, if the form type is email then you will be sent an email of with the visitors email address in it.

/**
	 * Decides if we send an email to the user or stores the email in the database
	 */
	public function process(){
		switch($this->form_type){
			default:
			case 'store':
				$return = $this->store_email();
			break;
			
			case 'email':
				$return = $this->send_email();
			break;
		}
		
		if(!$return){
			echo 'failed';		
		}
	}

Store The Email In A Database

/**
	 * Stores the users email to the db
	 */
	private function store_email(){
		$dbhost = 'localhost';
		$dbuser = 'root';
		$dbpass = '';
		
		//Connect to database
		$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
		
		$dbname = 'email_signup';
		mysql_select_db($dbname);
		
		//If table doesn't exist create it
		$this->check_table();
		
		//If it does exist check that email currently isn't in table
		if($this->insert_email()){
			//if it isnt insert new email and return successful	
			$return = true;
		} else {
			$return = false;
		}
		
		//Close database connection
		mysql_close($conn);
		
		return $return;
	}
	
	/**
	 * Checks to see if the table exists
	 * if it doesn't exists then creates the table
	 */
	private function check_table(){
		$sql = 'CREATE TABLE IF NOT EXISTS  `email_signup`.`email_signup` (
		`id` INT NOT NULL AUTO_INCREMENT ,
		`email` VARCHAR( 255 ) NOT NULL ,
		PRIMARY KEY (  `id` )
		) ENGINE = MYISAM ;';
		
		// Perform Query
		$result = mysql_query($sql);
		
		// Check result
		// This shows the actual query sent to MySQL, and the error. Useful for debugging.
		if (!$result) {
		    $message  = 'Invalid query: ' . mysql_error() . "\n";
		    $message .= 'Whole query: ' . $query;
		    die($message);
		}
	}
	
	/**
	 * Check to see if the email exists if it does return false else insert into table and return true
	 */
	private function insert_email(){
		$sql = sprintf("SELECT * FROM  `email_signup` WHERE  `email` = '%s'",
            mysql_real_escape_string($this->from_email));
            
            // Perform Query
		$result = mysql_query($sql);
		
		if(mysql_num_rows($result) > 0){
			return false;
		} else {
			$sql = "INSERT INTO `email_signup` (`email`) VALUES('".$this->from_email."')";

			// Perform Query
			$result_insert = mysql_query($sql);
			
			//If row has been inserted then returns true
			if(mysql_affected_rows() > 0){
				return true;
			}
		}
	}

Send Visitor Email Address To Admin Email

/**
	 * Sends the email of the signup
	 * 
	 * @returns
	 * success or failed
	 */
	private function send_email(){
		$subject = "New User submit email";
		$body = "A new user has submit their email address on your coming soon web page. The email is ".$this->from_email." save their email to keep them updated with the website.";
		 
		if (mail($this->to_, "Email from paulund.co.uk", $body)) {
		   return true;
		} else {
		   return false;
		}
	}

Advertise here

Comment