Create Ajax PHP Newsletter

A newsletter is very important for any website. You can increase your traffic, can sell more product and can follow up your website’s users using the newsletter. So, every ideal website should create a newsletter. If you create the newsletter and If you have newsletter subscriber then you can share your latest post to users using this newsletter.
Today I am going to show you how we create a newsletter using MySQL, ajax, PHP. Let’s see how we can create this.
At first, we create a newsletter subscribe form then we make a jquery function for request with jquery-ajax then we create a PHP script for subscribing user email using MySQL-PHP. We do this step by step.
Now we are going to create an index.php file for subscriber form and put this code into this file.
index.php

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">;
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Ajax php newsletter</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"; integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="asset/styles.css" media="all,print"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="asset/newsletter.shh.js"></script>
<script src="asset/jquery.cookie.js"></script>
<meta name="keywords" content="Ajax php newsletter"/>
<meta name="description" content="Ajax php newsletter tutorial"/>
</head>
<body align="center">
<div class="container">
<h1>Ajax php newsletter</h1>
<div id="subscribe_box">
<div class="title">GET TOP POSTS</div>
<center>
<b><big>Subscribe US</big></b><br/>&amp;<br/>
Get the best of all exclusive articles and updates to your email inbox.
</center>
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="subscriber_email">Email</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></div>
<input type="text" class="form-control" id="subscriber_email" placeholder="You Email Address">
</div>
</div>
<input type="submit" class="btn btn-primary" id="subscribe_newsletter" value="Subscribe">
</form>
<center>
we always respect your privacy and take protecting it seriously.
</center>
</div>
<div id="subscribe_message"></div>
</div>
<div style="align:center;font-weight:bold;font-size:15px;">phpans.com</div>
</body>
</html>

Now we create a directory name as the asset and make jquery ajax function name as newsletter.shh.js we already linked it into our index.php file.
newsletter.shh.js

$(document).ready(function() {

function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,4}$/i);
return pattern.test(emailAddress);
};

// Cookie Start

var subscribed = $.cookie('subscribed');
if (subscribed=='true')
{
$('#subscribe_box').hide();
}
else
{

$('#subscribe_newsletter').click(function()
{
var value= 1;
var mail=$("#subscriber_email").val();
var dataString = 'action=subscribe&email='+mail;
if($.trim(mail).length>0 && isValidEmailAddress(mail))
{
$.ajax({
type: "POST",
url: "subscribe.php",
data: dataString,
cache: false,
beforeSend: function(){
$('#subscriber_email').attr("disabled", true);
$('#subscribe_newsletter').attr("disabled", true);
$("#subscribe_newsletter").val('Loading...');
$('#subscribe_newsletter').removeClass();
$('#subscribe_newsletter').addClass('btn');
$('#subscribe_newsletter').addClass('btn-warning');
},
success: function(data){
if(data)
{
if(data=='true')
{
$.cookie('subscribed', 'true', { expires: 30, path: '/' });
// $.removeCookie('subscribed');
$('#subscribe_message').removeClass();
$('#subscribe_message').addClass('success_message');
$("#subscribe_message").html("<span class='glyphicon glyphicon glyphicon-ok'></span> You have Susscessfully subscribed");
$('#subscribe_message').fadeIn().delay(3000).fadeOut();
$('#subscriber_email').hide();
$('#subscribe_newsletter').hide();
$('#subscribe_box').html("<b><span class='glyphicon glyphicon glyphicon-thumbs-up'></span> Thankyou for subscribe our newsletter.</b>");
}
else if(data=='exists')
{
$('#subscribe_message').removeClass();
$('#subscribe_message').addClass('error_message');
$("#subscribe_message").html("<span class='glyphicon glyphicon glyphicon-exclamation-sign'></span> You are already subscribed.");
}
else
{
$('#subscribe_message').removeClass();
$('#subscribe_message').addClass('error_message');
$("#subscribe_message").html("<span class='glyphicon glyphicon glyphicon-exclamation-sign'></span> There is a SQL error please notify admin about this error.");
$('#subscribe_message').fadeIn().delay(3000).fadeOut();

}
$('#subscriber_email').attr("disabled", false);
$('#subscribe_newsletter').attr("disabled", false);
$("#subscribe_newsletter").val('Subscribe');
$('#subscribe_message').removeClass();
$('#subscribe_message').addClass('btn');
$('#subscribe_message').addClass('btn-success')
}
else
{
$('#subscriber_email').attr("disabled", false);
$('#subscribe_newsletter').attr("disabled", false);
$('#subscribe_newsletter').removeClass();
$('#subscribe_newsletter').addClass('btn')
$('#subscribe_newsletter').addClass('btn-danger');
$("#subscribe_newsletter").val('Subscribe');
$('#subscribe_message').removeClass();
$('#subscribe_message').addClass('error_message');
$("#subscribe_message").html("There is an error!");
$('#subscribe_message').fadeIn().delay(5000).fadeOut();
}
}

});

}
else
{
$('#subscribe_message').addClass('error_message');
$("#subscribe_message").html("<span class='glyphicon glyphicon glyphicon-exclamation-sign'></span> Please type a valid email address!");
$('#subscribe_message').fadeIn().delay(5000).fadeOut();
}
return false;
});
}

});

Now create a stylesheet for this script. Create a styles.css file into asset directory and put this styles into this file.
styles.css

body
{
background-color: #D2E0E8;
}
.error_message
{
background-color: #FF0000;
padding: 10px;
color: #FFF;
border-radius: 5px;
-moz-border-radius: 5px;
-o-border-radius: 5px;
-webkit-border-radius: 5px;
}
#result
{
font-size: 20px;
font-weight:bold;
}
.title
{
background-color: #F3F8FA;
font-size: 20px;
font-weight: bold;
}
We recently created index.php , stylesheet & jquery ajax function. Now download a jquery cookie function into and set put this file into asset directory for set cookie if anyone subscribed. Now we create a MySQL php script for saving data into out database. First, we should create a table into our database. This is SQL command for creating new table for a database table. We provide SQL file into the script you can insert this also.

CREATE TABLE IF NOT EXISTS `shh_subscribers` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`ip` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251 AUTO_INCREMENT=1 ;
Create a config file for connecting database with our php file. We create this config file name as config.shh.php and put this code.
<?php
date_default_timezone_set('UTC');
$dbname = "test";
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
function connectdb()
{
global $dbname, $dbuser, $dbhost, $dbpass;
$conms = @mysql_connect($dbhost,$dbuser,$dbpass);
if(!$conms) return false;
$condb = @mysql_select_db($dbname);
if(!$condb) return false;
return true;
}
connectdb();
?>
Now we are going to make subscriber script into php. Create a subscriber.php file and put this code into this file 
<?php
include('config.shh.php');
if (isset($_POST['email']) && connectdb())
{
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM shh_subscribers WHERE email='".$email."'"));
if ($count[0]==0)
{
$res = mysql_query("INSERT INTO shh_subscribers SET email='".$email."', ip='".$ip."'");
if($res)
{
print 'true';
}
else
{
print 'false';
}

}
else
{
print 'exists';
}
}
?>
We created this script successfully. Now we can run this script. Run this script on your server. This is ready for using.
Download Source Code
Unlock source code with a social share.

Did you like this article? it will be appreciated if you share a coffee or burger with the author

Sent $5 to the author
Sent $10 to the author

Need Assistance?

I'm Sajjad Hossain, working on web application development since 2012. Do you need assistance on your project? or are you stuck with problems? I am available to help you.
If you want to contact with me ping me at -

WhatsApp
Skype


We use cookies on our website. To find out more about how and why they are used or opt-out, please read our Cookie Policy. By choosing "I Accept", you consent to our use of cookies. Cookie Policy
Top