Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Newsletter signup

Featured Replies

Ok, does this make sense to anyone here? http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/

 

I have always struggled with databases but this is beyond a joke, I set up a database but to be honest I don't think I did it right as the form just doesn't seem to do anything.

It might sound stupid. But did you include your database connection details here:

 

if($_GET['action'] == 'signup'){
   mysql_connect('localhost','YOUR DB USERNAME','YOUR DB PASSWORD');
   mysql_select_db('YOUR DATABASE THAT CONTAINS THE SIGNUPS TABLE');
   $email = mysql_real_escape_string($_POST['signup-email']);

   //do some stuff

   exit;
}

  • Author

It might sound stupid. But did you include your database connection details here:

 

if($_GET['action'] == 'signup'){
   mysql_connect('localhost','YOUR DB USERNAME','YOUR DB PASSWORD');
   mysql_select_db('YOUR DATABASE THAT CONTAINS THE SIGNUPS TABLE');
   $email = mysql_real_escape_string($_POST['signup-email']);

   //do some stuff

   exit;
}

 

Yeah, this is where I think I'm going wrong

if($_GET['action'] == 'signup'){

mysql_connect('localhost','web100-signup','password');  
mysql_select_db('signup');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);

 

Obv password isn't shown on this forum and the rest of the script is below it.

Edited by roothost

And you're sure you added the table structure to your database?

 

CREATE TABLE `signups` (
 `signups_id` int(10) NOT NULL AUTO_INCREMENT,
 `signup_email_address` varchar(250) DEFAULT NULL,
 `signup_date` date DEFAULT NULL,
 `signup_time` time DEFAULT NULL,
 PRIMARY KEY (`signups_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 

Another option would be to actually test if your connection details are actually allowing you to connect:

In another page or something try this:

<?php
mysql_connect("localhost", "USERNAME", "PASSWORD") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("DATABASE NAME") or die(mysql_error());
echo "Connected to Database";
?>

 

Other than that i'm not sure. I set this up locally on WAMP, did it in about 2 minutes (literally) and everything worked fine for me.

  • Author

And you're sure you added the table structure to your database?

 

CREATE TABLE `signups` (
 `signups_id` int(10) NOT NULL AUTO_INCREMENT,
 `signup_email_address` varchar(250) DEFAULT NULL,
 `signup_date` date DEFAULT NULL,
 `signup_time` time DEFAULT NULL,
 PRIMARY KEY (`signups_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 

Another option would be to actually test if your connection details are actually allowing you to connect:

In another page or something try this:

<?php
mysql_connect("localhost", "USERNAME", "PASSWORD") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("DATABASE NAME") or die(mysql_error());
echo "Connected to Database";
?>

 

Other than that i'm not sure. I set this up locally on WAMP, did it in about 2 minutes (literally) and everything worked fine for me.

http://www.simonvincent.co.uk/test.php - seems to connect fine, which would point to me not setting up the table correctly? Visit the root and you will see what I mean about it just says please wait.

 

I had a script before that built the database table via a php file, you wouldn;t happen to know what I mean do you? You just put the information above in and somehow it creates it.

Edited by roothost

  • Author

Working on the test server now, thank god! Now to transfer to the live site. Bed first though!

I had a script before that built the database table via a php file, you wouldn;t happen to know what I mean do you? You just put the information above in and somehow it creates it.

Yeah, I believe IPB's initial installation comes with something like that. Just put the database info in and it populates everything for you.

  • Author

Yeah, I believe IPB's initial installation comes with something like that. Just put the database info in and it populates everything for you.

IPB?

 

Would it be possible to add a name field to this as well? I did attempt it but no matter what settings I gave it, it just wouldn't store the name. The field was there in the database, just not the content.

IPB?

 

Would it be possible to add a name field to this as well? I did attempt it but no matter what settings I gave it, it just wouldn't store the name. The field was there in the database, just not the content.

IPB - It's a forums software that these forums use.

 

Sure is possible to add another field to the table. What do you want done? Maybe I can help.

  • Author

IPB - It's a forums software that these forums use.

 

Sure is possible to add another field to the table. What do you want done? Maybe I can help.

Well I added a signup_name field to the mySQL database, and the form but thye database wasn't collecting the name, just the email. This is what I have, without the signup_name field;

CREATE TABLE `signups` (
 `signups_id` int(10) NOT NULL AUTO_INCREMENT,
 `signup_email_address` varchar(250) DEFAULT NULL,
 `signup_date` date DEFAULT NULL,
 `signup_time` time DEFAULT NULL,
 PRIMARY KEY (`signups_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

What settings should I be using for this field? Same as the signup_email_address?

 

And this is the full php/js and html;

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

mysql_connect('localhost','edited','edited');  
mysql_select_db('edited');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);

//validate email address - check if input was empty
if(empty($email)){
	$status = "error";
	$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
		$status = "error";
		$message = "You have entered an invalid email address!";
}
else {
	$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
	if(mysql_num_rows($existingSignup) < 1){

		$date = date('Y-m-d');
		$time = date('H:i:s');

		$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
		if($insertSignup){ //if insert is successful
			$status = "success";
			$message = "You have been signed up!";	
		}
		else { //if insert fails
			$status = "error";
			$message = "Ooops, Theres been a technical error!";	
		}
	}
	else { //if already signed up
		$status = "error";
		$message = "This email address has already been registered!";
	}
}

//return json response
$data = array(
	'status' => $status,
	'message' => $message
);

echo json_encode($data);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax & JSON Email Singup Form</title>

<!-- We will get our jQuery from google -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('jquery', '1.4.1');
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#newsletter-signup').submit(function(){

	//check the form is not currently submitting
	if($(this).data('formstatus') !== 'submitting'){

		//setup variables
		var form = $(this),
			formData = form.serialize(),
			formUrl = form.attr('action'),
			formMethod = form.attr('method'), 
			responseMsg = $('#signup-response');

		//add status data to form
		form.data('formstatus','submitting');

		//show response message - waiting
		responseMsg.hide()
				   .addClass('response-waiting')
				   .text('Please Wait...')
				   .fadeIn(200);

		//send data to server for validation
		$.ajax({
			url: formUrl,
			type: formMethod,
			data: formData,
			success:function(data){

				//setup variables
				var responseData = jQuery.parseJSON(data), 
					klass = '';

				//response conditional
				switch(responseData.status){
					case 'error':
						klass = 'response-error';
					break;
					case 'success':
						klass = 'response-success';
					break;	
				}

				//show reponse message
				responseMsg.fadeOut(200,function(){
					$(this).removeClass('response-waiting')
						   .addClass(klass)
						   .text(responseData.message)
						   .fadeIn(200,function(){
							   //set timeout to hide response message
							   setTimeout(function(){
								   responseMsg.fadeOut(200,function(){
								       $(this).removeClass(klass);
									   form.data('formstatus','idle');
								   });
							   },3000)
							});
				});
			}
		});
	}

	//prevent form from submitting
	return false;
});
});
</script>
</head>

<body>

<form id="newsletter-signup" action="?action=signup" method="post">
   <fieldset>
       <label for="signup-email">Sign up for email offers, news & events:</label>
       <input type="text" name="signup-email" id="signup-email" />
       <input type="submit" id="signup-button" value="Sign Me Up!" />
       <p id="signup-response"></p>
   </fieldset>
</form>

</body>
</html>

 

Obviously, I just add another form field for signup name, but not sure what else as I did that and although the field appeared and I was able to enter the name, this wasn't saved in the database.

 

Thanks in advance for any help on this.

You need to get the POSTed string from the form and include it in part of your mysql query.

 

$name  = mysql_real_escape_string($_POST['signup-name']);

in this case the 'name' of your input field is 'signup-name' and you store it in the $name variable.

 

then you include it in your query

 

$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time, signup_name) VALUES ('$email','$date','$time','$name')");

 

I remade it and styled it a little so you can just copy and paste if ya want. :)

 

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

mysql_connect('localhost','username','password');  
mysql_select_db('database');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
$name  = mysql_real_escape_string($_POST['signup-name']);

//validate email address - check if input was empty
if(empty($email)){
	$status = "error";
	$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
		$status = "error";
		$message = "You have entered an invalid email address!";
}
else {
	$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
	if(mysql_num_rows($existingSignup) < 1){

		$date = date('Y-m-d');
		$time = date('H:i:s');

		$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time, signup_name) VALUES ('$email','$date','$time','$name')");
		if($insertSignup){ //if insert is successful
			$status = "success";
			$message = "You have been signed up!";	
		}
		else { //if insert fails
			$status = "error";
			$message = "Ooops, Theres been a technical error!";	
		}
	}
	else { //if already signed up
		$status = "error";
		$message = "This email address has already been registered!";
	}
}

//return json response
$data = array(
	'status' => $status,
	'message' => $message
);

echo json_encode($data);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax & JSON Email Singup Form</title>

<style type="text/css">

/* Qucik and dirty. I normally use a custom css reset and would not advise using the below. But for the purposes of this tutorial it should be fine. */

* { 
padding:0;
margin:0;
}

body {
font-size:12px;
font-family:Arial, Helvetica, sans-serif;	
}

fieldset {
border:none;	
}

form {
width:930px;
margin:20% auto;	
padding:15px;
border:solid 6px #9FCBFF;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
}

input {
border:none;
background-color:none;	
}

#signup-email {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin-left:10px;
margin-right:4px;
}

#signup-email:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-name {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin: 0px 4px 10px 10px;
}

#signup-name:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-button {
background-color:#9FCBFF;
color:#FFF;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
padding:5px;
text-shadow: 1px 1px 1px #5FA8FF;	
}

#signup-button:hover {
cursor:pointer;
background-color:#7FB9FF;
}

#signup-response {
display:inline;
margin-left:4px;
padding-left:20px;
}

.response-waiting {
background:url("loading.gif") no-repeat;
}

.response-success {
background:url("tick.png") no-repeat;
}

.response-error {
background:url("cross.png") no-repeat;
}

</style>

<!-- We will get our jQuery from google -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('jquery', '1.4.1');
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#newsletter-signup').submit(function(){

	//check the form is not currently submitting
	if($(this).data('formstatus') !== 'submitting'){

		//setup variables
		var form = $(this),
			formData = form.serialize(),
			formUrl = form.attr('action'),
			formMethod = form.attr('method'), 
			responseMsg = $('#signup-response');

		//add status data to form
		form.data('formstatus','submitting');

		//show response message - waiting
		responseMsg.hide()
				   .addClass('response-waiting')
				   .text('Please Wait...')
				   .fadeIn(200);

		//send data to server for validation
		$.ajax({
			url: formUrl,
			type: formMethod,
			data: formData,
			success:function(data){

				//setup variables
				var responseData = jQuery.parseJSON(data), 
					klass = '';

				//response conditional
				switch(responseData.status){
					case 'error':
						klass = 'response-error';
					break;
					case 'success':
						klass = 'response-success';
					break;	
				}

				//show reponse message
				responseMsg.fadeOut(200,function(){
					$(this).removeClass('response-waiting')
						   .addClass(klass)
						   .text(responseData.message)
						   .fadeIn(200,function(){
							   //set timeout to hide response message
							   setTimeout(function(){
								   responseMsg.fadeOut(200,function(){
								       $(this).removeClass(klass);
									   form.data('formstatus','idle');
								   });
							   },3000)
							});
				});
			}
		});
	}

	//prevent form from submitting
	return false;
});
});
</script>
</head>

<body>

<form id="newsletter-signup" action="?action=signup" method="post">
   <fieldset>
	<label for="signup-name">Enter name here:</label>
       <input type="text" name="signup-name" id="signup-name" /> <br>
       <label for="signup-email">Sign up for email offers, news & events:</label>
       <input type="text" name="signup-email" id="signup-email" />

       <input type="submit" id="signup-button" value="Sign Me Up!" />
       <p id="signup-response"></p>
   </fieldset>
</form>

</body>
</html>

 

EDIT: I didn't include any validation rules, so you might want to consider that.

Edited by Samus

  • Author

You need to get the POSTed string from the form and include it in part of your mysql query.

 

$name  = mysql_real_escape_string($_POST['signup-name']);

in this case the 'name' of your input field is 'signup-name' and you store it in the $name variable.

 

then you include it in your query

 

$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time, signup_name) VALUES ('$email','$date','$time','$name')");

 

I remade it and styled it a little so you can just copy and paste if ya want. :)

 

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

mysql_connect('localhost','username','password');  
mysql_select_db('database');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
$name  = mysql_real_escape_string($_POST['signup-name']);

//validate email address - check if input was empty
if(empty($email)){
	$status = "error";
	$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
		$status = "error";
		$message = "You have entered an invalid email address!";
}
else {
	$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
	if(mysql_num_rows($existingSignup) < 1){

		$date = date('Y-m-d');
		$time = date('H:i:s');

		$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time, signup_name) VALUES ('$email','$date','$time','$name')");
		if($insertSignup){ //if insert is successful
			$status = "success";
			$message = "You have been signed up!";	
		}
		else { //if insert fails
			$status = "error";
			$message = "Ooops, Theres been a technical error!";	
		}
	}
	else { //if already signed up
		$status = "error";
		$message = "This email address has already been registered!";
	}
}

//return json response
$data = array(
	'status' => $status,
	'message' => $message
);

echo json_encode($data);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax & JSON Email Singup Form</title>

<style type="text/css">

/* Qucik and dirty. I normally use a custom css reset and would not advise using the below. But for the purposes of this tutorial it should be fine. */

* { 
padding:0;
margin:0;
}

body {
font-size:12px;
font-family:Arial, Helvetica, sans-serif;	
}

fieldset {
border:none;	
}

form {
width:930px;
margin:20% auto;	
padding:15px;
border:solid 6px #9FCBFF;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
}

input {
border:none;
background-color:none;	
}

#signup-email {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin-left:10px;
margin-right:4px;
}

#signup-email:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-name {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin: 0px 4px 10px 10px;
}

#signup-name:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-button {
background-color:#9FCBFF;
color:#FFF;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
padding:5px;
text-shadow: 1px 1px 1px #5FA8FF;	
}

#signup-button:hover {
cursor:pointer;
background-color:#7FB9FF;
}

#signup-response {
display:inline;
margin-left:4px;
padding-left:20px;
}

.response-waiting {
background:url("loading.gif") no-repeat;
}

.response-success {
background:url("tick.png") no-repeat;
}

.response-error {
background:url("cross.png") no-repeat;
}

</style>

<!-- We will get our jQuery from google -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('jquery', '1.4.1');
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#newsletter-signup').submit(function(){

	//check the form is not currently submitting
	if($(this).data('formstatus') !== 'submitting'){

		//setup variables
		var form = $(this),
			formData = form.serialize(),
			formUrl = form.attr('action'),
			formMethod = form.attr('method'), 
			responseMsg = $('#signup-response');

		//add status data to form
		form.data('formstatus','submitting');

		//show response message - waiting
		responseMsg.hide()
				   .addClass('response-waiting')
				   .text('Please Wait...')
				   .fadeIn(200);

		//send data to server for validation
		$.ajax({
			url: formUrl,
			type: formMethod,
			data: formData,
			success:function(data){

				//setup variables
				var responseData = jQuery.parseJSON(data), 
					klass = '';

				//response conditional
				switch(responseData.status){
					case 'error':
						klass = 'response-error';
					break;
					case 'success':
						klass = 'response-success';
					break;	
				}

				//show reponse message
				responseMsg.fadeOut(200,function(){
					$(this).removeClass('response-waiting')
						   .addClass(klass)
						   .text(responseData.message)
						   .fadeIn(200,function(){
							   //set timeout to hide response message
							   setTimeout(function(){
								   responseMsg.fadeOut(200,function(){
								       $(this).removeClass(klass);
									   form.data('formstatus','idle');
								   });
							   },3000)
							});
				});
			}
		});
	}

	//prevent form from submitting
	return false;
});
});
</script>
</head>

<body>

<form id="newsletter-signup" action="?action=signup" method="post">
   <fieldset>
	<label for="signup-name">Enter name here:</label>
       <input type="text" name="signup-name" id="signup-name" /> <br>
       <label for="signup-email">Sign up for email offers, news & events:</label>
       <input type="text" name="signup-email" id="signup-email" />

       <input type="submit" id="signup-button" value="Sign Me Up!" />
       <p id="signup-response"></p>
   </fieldset>
</form>

</body>
</html>

 

EDIT: I didn't include any validation rules, so you might want to consider that.

Mate, that works a treat. I didnt expect you to do all that, I owe you one.

 

Got your email as well.

Mate, that works a treat. I didnt expect you to do all that, I owe you one.

 

Got your email as well.

twas a fake one, you can inbox me if you want my real one though.

  • Author

twas a fake one, you can inbox me if you want my real one though.

Yeah, I will do.

 

It's taking the p*** I know, but would it be possible for it to be modified somehow so the user who signs up receives an 'welcome' email?

Yeah, I will do.

 

It's taking the p*** I know, but would it be possible for it to be modified somehow so the user who signs up receives an 'welcome' email?

Sure I like doing these things. I'll run some tests then reply here once i've set it up.

Updated version:

 

I simply added variables to include in the mail() function parameters.

Added the following:

$subject = "Mailing list";
$emessage = "Hi ".$name.", thank you for signing up to my mailing list. Please be sure to contact <a href='mailto:edited?Subject=Samus%20you're%20awesome'>Samus</a>";
$from = "michaelsite12@gmail.com";
$header = "From: ".$from;

 

and mail function at end of the script.

mail($email,$subject,$emessage,$header);

 

Here's full updated code..

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

mysql_connect('localhost',edited,'edited');  
mysql_select_db('edited');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
$name  = mysql_real_escape_string($_POST['signup-name']);
$subject = "Mailing list";
$emessage = "Hi ".$name.", thank you for signing up to my mailing list. Please be sure to contact <a href='mailto:michaelsite23@gmail.com?Subject=Samus%20you're%20awesome'>Samus</a>";
$from = "edited";
$header = "From: ".$from;

//validate email address - check if input was empty
if(empty($email)){
	$status = "error";
	$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
		$status = "error";
		$message = "You have entered an invalid email address!";
}
else {
	$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
	if(mysql_num_rows($existingSignup) < 1){

		$date = date('Y-m-d');
		$time = date('H:i:s');

		$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time, signup_name) VALUES ('$email','$date','$time','$name')");
		if($insertSignup){ //if insert is successful
			$status = "success";
			$message = "You have been signed up!";	

		}
		else { //if insert fails
			$status = "error";
			$message = "Ooops, Theres been a technical error!";	
		}
	}
	else { //if already signed up
		$status = "error";
		$message = "This email address has already been registered!";
	}
}

//return json response
$data = array(
	'status' => $status,
	'message' => $message
);

echo json_encode($data);	
mail($email,$subject,$emessage,$header);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax & JSON Email Singup Form</title>

<style type="text/css">

/* Qucik and dirty. I normally use a custom css reset and would not advise using the below. But for the purposes of this tutorial it should be fine. */

* { 
padding:0;
margin:0;
}

body {
font-size:12px;
font-family:Arial, Helvetica, sans-serif;	
}

fieldset {
border:none;	
}

form {
width:930px;
margin:20% auto;	
padding:15px;
border:solid 6px #9FCBFF;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
}

input {
border:none;
background-color:none;	
}

#signup-email {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin-left:10px;
margin-right:4px;
}

#signup-email:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-name {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin: 0px 4px 10px 10px;
}

#signup-name:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-button {
background-color:#9FCBFF;
color:#FFF;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
padding:5px;
text-shadow: 1px 1px 1px #5FA8FF;	
}

#signup-button:hover {
cursor:pointer;
background-color:#7FB9FF;
}

#signup-response {
display:inline;
margin-left:4px;
padding-left:20px;
}

.response-waiting {
background:url("loading.gif") no-repeat;
}

.response-success {
background:url("tick.png") no-repeat;
}

.response-error {
background:url("cross.png") no-repeat;
}

</style>

<!-- We will get our jQuery from google -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('jquery', '1.4.1');
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#newsletter-signup').submit(function(){

	//check the form is not currently submitting
	if($(this).data('formstatus') !== 'submitting'){

		//setup variables
		var form = $(this),
			formData = form.serialize(),
			formUrl = form.attr('action'),
			formMethod = form.attr('method'), 
			responseMsg = $('#signup-response');

		//add status data to form
		form.data('formstatus','submitting');

		//show response message - waiting
		responseMsg.hide()
				   .addClass('response-waiting')
				   .text('Please Wait...')
				   .fadeIn(200);

		//send data to server for validation
		$.ajax({
			url: formUrl,
			type: formMethod,
			data: formData,
			success:function(data){

				//setup variables
				var responseData = jQuery.parseJSON(data), 
					klass = '';

				//response conditional
				switch(responseData.status){
					case 'error':
						klass = 'response-error';
					break;
					case 'success':
						klass = 'response-success';
					break;	
				}

				//show reponse message
				responseMsg.fadeOut(200,function(){
					$(this).removeClass('response-waiting')
						   .addClass(klass)
						   .text(responseData.message)
						   .fadeIn(200,function(){
							   //set timeout to hide response message
							   setTimeout(function(){
								   responseMsg.fadeOut(200,function(){
								       $(this).removeClass(klass);
									   form.data('formstatus','idle');
								   });
							   },3000)
							});
				});
			}
		});
	}

	//prevent form from submitting
	return false;
});
});
</script>
</head>

<body>

<form id="newsletter-signup" action="?action=signup" method="post">
   <fieldset>
	<label for="signup-name">Enter name here:</label>
       <input type="text" name="signup-name" id="signup-name" /> <br>
       <label for="signup-email">Sign up for email offers, news & events:</label>
       <input type="text" name="signup-email" id="signup-email" />

       <input type="submit" id="signup-button" value="Sign Me Up!" />
       <p id="signup-response"></p>
   </fieldset>
</form>

</body>
</html>

Edited by zed

  • Author

Updated version:

 

I simply added variables to include in the mail() function parameters.

Added the following:

$subject = "Mailing list";
$emessage = "Hi ".$name.", thank you for signing up to my mailing list. Please be sure to contact <a href='mailto:blah?Subject=Samus%20you're%20awesome'>Samus</a>";
$from = "michaelsite12@gmail.com";
$header = "From: ".$from;

 

and mail function at end of the script.

mail($email,$subject,$emessage,$header);

 

Here's full updated code..

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

mysql_connect('localhost',edited,'edited');  
mysql_select_db('edited');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
$name  = mysql_real_escape_string($_POST['signup-name']);
$subject = "Mailing list";
$emessage = "Hi ".$name.", thank you for signing up to my mailing list. Please be sure to contact <a href='mailto:edited?Subject=Samus%20you're%20awesome'>Samus</a>";
$from = "michaelsite12@gmail.com";
$header = "From: ".$from;

//validate email address - check if input was empty
if(empty($email)){
	$status = "error";
	$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
		$status = "error";
		$message = "You have entered an invalid email address!";
}
else {
	$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
	if(mysql_num_rows($existingSignup) < 1){

		$date = date('Y-m-d');
		$time = date('H:i:s');

		$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time, signup_name) VALUES ('$email','$date','$time','$name')");
		if($insertSignup){ //if insert is successful
			$status = "success";
			$message = "You have been signed up!";	

		}
		else { //if insert fails
			$status = "error";
			$message = "Ooops, Theres been a technical error!";	
		}
	}
	else { //if already signed up
		$status = "error";
		$message = "This email address has already been registered!";
	}
}

//return json response
$data = array(
	'status' => $status,
	'message' => $message
);

echo json_encode($data);	
mail($email,$subject,$emessage,$header);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax & JSON Email Singup Form</title>

<style type="text/css">

/* Qucik and dirty. I normally use a custom css reset and would not advise using the below. But for the purposes of this tutorial it should be fine. */

* { 
padding:0;
margin:0;
}

body {
font-size:12px;
font-family:Arial, Helvetica, sans-serif;	
}

fieldset {
border:none;	
}

form {
width:930px;
margin:20% auto;	
padding:15px;
border:solid 6px #9FCBFF;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
}

input {
border:none;
background-color:none;	
}

#signup-email {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin-left:10px;
margin-right:4px;
}

#signup-email:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-name {
border:1px solid #999999;
color:#9E9E9E;
padding:5px;
margin: 0px 4px 10px 10px;
}

#signup-name:focus {
border-color:#9FCBFF;
background-color:#DFEEFF;
background-image:none;
color:#000;
}

#signup-button {
background-color:#9FCBFF;
color:#FFF;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
padding:5px;
text-shadow: 1px 1px 1px #5FA8FF;	
}

#signup-button:hover {
cursor:pointer;
background-color:#7FB9FF;
}

#signup-response {
display:inline;
margin-left:4px;
padding-left:20px;
}

.response-waiting {
background:url("loading.gif") no-repeat;
}

.response-success {
background:url("tick.png") no-repeat;
}

.response-error {
background:url("cross.png") no-repeat;
}

</style>

<!-- We will get our jQuery from google -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('jquery', '1.4.1');
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#newsletter-signup').submit(function(){

	//check the form is not currently submitting
	if($(this).data('formstatus') !== 'submitting'){

		//setup variables
		var form = $(this),
			formData = form.serialize(),
			formUrl = form.attr('action'),
			formMethod = form.attr('method'), 
			responseMsg = $('#signup-response');

		//add status data to form
		form.data('formstatus','submitting');

		//show response message - waiting
		responseMsg.hide()
				   .addClass('response-waiting')
				   .text('Please Wait...')
				   .fadeIn(200);

		//send data to server for validation
		$.ajax({
			url: formUrl,
			type: formMethod,
			data: formData,
			success:function(data){

				//setup variables
				var responseData = jQuery.parseJSON(data), 
					klass = '';

				//response conditional
				switch(responseData.status){
					case 'error':
						klass = 'response-error';
					break;
					case 'success':
						klass = 'response-success';
					break;	
				}

				//show reponse message
				responseMsg.fadeOut(200,function(){
					$(this).removeClass('response-waiting')
						   .addClass(klass)
						   .text(responseData.message)
						   .fadeIn(200,function(){
							   //set timeout to hide response message
							   setTimeout(function(){
								   responseMsg.fadeOut(200,function(){
								       $(this).removeClass(klass);
									   form.data('formstatus','idle');
								   });
							   },3000)
							});
				});
			}
		});
	}

	//prevent form from submitting
	return false;
});
});
</script>
</head>

<body>

<form id="newsletter-signup" action="?action=signup" method="post">
   <fieldset>
	<label for="signup-name">Enter name here:</label>
       <input type="text" name="signup-name" id="signup-name" /> <br>
       <label for="signup-email">Sign up for email offers, news & events:</label>
       <input type="text" name="signup-email" id="signup-email" />

       <input type="submit" id="signup-button" value="Sign Me Up!" />
       <p id="signup-response"></p>
   </fieldset>
</form>

</body>
</html>

You, sir, are a legend!! :clapping:

 

You have helped me no end tonight, much appreciated.

Edited by zed

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.