Ajax is a popular technology in web development with the combination of Javascript and DOM, Ajax will do wonders. Here I’m not talking about ajax technology, just explaining how newsletter signup can be done with ajax and core javascript along with PHP. In this example I have used onclick javascript event to call an Ajax request.
Create an HTML page, say for example newsletter.html which is the user communication page and ajax.js javascript page for handling client side scripting and finally ajax.php for communicating with server.
Add the below HTML Code in newsletter.html
Here "newsletter_signup" is an unique process name, which i have used for handling the request based on the process name. And div id divSignupMessage used for displaying the output received from server.
Now create another file called ajax.js and add the below code into it.
function xmlhttpPost(url,method,divname,qstr){
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest){
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject){
self.xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
}
self.xmlHttpReq.open(method, url, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function(){
if (self.xmlHttpReq.readyState == 4){
updateDiv(self.xmlHttpReq.responseText,divname);//div update function call
}
}
self.xmlHttpReq.send(qstr);
}
//Updating output
function updateDiv(txtvalue,divname){
if(divname){
document.getElementById(divname).innerHTML='';
document.getElementById(divname).innerHTML=txtvalue;
}
}
function ajaxRequest(process,divname){
if(process =='newsletter_signup'){
email = document.getElementById('email').value;
qstr = 'p=' + escape(process) + '&email=' + escape(email);
xmlhttpPost('ajax.php','POST',divname,qstr);
}
}
Finally add below PHP Code in ajax.php file.
$output = "";
if($process == "newsletter_signup"){$email = mysql_real_escape_string(trim($_REQUEST["email"]));
$email_validation = ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $email);
if($email_validation<1){//Email validation error message
$output = "Please enter valid email address";
}elseif($email_validation>=1){ //Already exist email error message
$sql = "SELECT `email` FROM `newsletter` WHERE `email`=".$email." LIMIT 1";
$res = mysql_query($sql);
$tot = mysql_num_rows($res);
if($tot>0){
$output = "Email address already exist";
}else{
$output = "TRUE";
}
}
echo $output;
exit;
}//End
Check out the online example and download the working example.