Search This Blog

Sunday, October 20, 2013

Creating Custom Scrollbar with jQuery

Custom vertical / horizontal scroll bars is a nice and unique features for websites, as a web developer or designer we can apply this features in our web projects to become our projects unique.
Most websites using custom scroll bar areFacebook, Twitter and Google Gmail, So what they secrets to create custom scroll bar?
In the web there have many available ready to use plugins of this web application, but how to create our own code? In this tutorial I would like share our own idea on how to create a custom vertical scroll bar with jQuery.
This custom scroll bar we will create are have similarity on Facebook and Google GmailScroll bar. So let’s begin.

1. Creating the Page Template

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Creating Custom Vertical Scrollbar with jQuery | istockphp.com</title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="js/jquery-1.9.1.js"> </script>
<script type="text/javascript" src="js/jquery.mousewheel.js"> </script>
<script type="text/javascript" src="js/jquery-ui-draggable.js"> </script>
<script type="text/javascript" src="js/script.js"></script>
</head>

<body>
	<div id="wrapper">
		<div id="scroll_block">
			<div id="scrollbar_holder">
            	<div class="scrollbar"></div>
            </div>
			<div id="scroll_content">
                    <div id="content" align="justify">
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <br />
                        <p>
                        Hello istockphp, Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
                        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
                        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
                        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
                        feugiat vitae, ultricies eget, tempor sit amet, ante.
                        </p>
                        <p>
                        2013 &copy; Work by <a href="http://istockphp.com">istockphp.com</a><br />
                        <br />
                        Support us our social fan pages, we inspire to create more.
                        <br />
                        <strong>Facebook: </strong><a href="http://www.facebook.com/pages/Istockphp/235451993242578">http://www.facebook.com/pages/Istockphp/235451993242578</a><br />
                        <strong>Twitter:</strong> <a href="http://twitter.com/istockphp">http://twitter.com/istockphp</a><br />
                        <strong>Google Plus:</strong> <a href="https://plus.google.com/104655767794822143257">https://plus.google.com/104655767794822143257</a><br />
                        </p>
                        <br />
                    </div> <!--content end-->
               </div> <!--scroll_content end-->
      </div> <!--scroll_block end-->
    </div> <!--wrapper end-->
</body>
</html>
In the index.html we included the stylesheet and the jQuery script, to complete this web application fast and easy we need to include the jquery.mousewheel.js to get the trigger of mouse scroll event and jquery-ui-draggable.js for drag gable trigger event and lastly our custom jQuery script.

2. The stylesheet

style.css
body {
	font-family: Arial, Helvetica, sans-serif;
	font-size:13px;
	margin:0;
	padding:0
}
div#scroll_block {
	width: 500px;
    height: 500px;
    overflow:hidden; /* hide the scroll bar*/
	margin: 20px auto 0 auto;
	background:#E4E7F0;
	position:relative;
}
div#scroll_content {
    height: 500px;
    width: 485px;
	position:relative;
}
div#scrollbar_holder {
   	background: #ced0d3;
	border-radius:8px;
	float: right;
    width: 15px;
	position:absolute;
	right:0;
}
div#content {
	padding: 0 14px;
}
div.scrollbar {
	background: #7c7d7f;
	border-radius:8px;
	width: 15px;
	top:0;
}
In stylesheet, in the div#scroll_block we need to set overflow hidden to hide the contents and the div#scrollbar_holder we set to position absolute and float right for scroll bar holder.

3. The jQuery script

script.js
/*
	Author: Axl Mulat
	Site: http://istockphp.com
*/
jQuery(function($) {

	var scrollBlockHeight = $("div#scroll_block").height(); // get height
	$("div#scrollbar_holder").height(scrollBlockHeight); // set height for scroll holder

	var contentHeight 	= $("div#content").height(); // get content div height
	// formula custom scroll bar
	var scrollbarHeight = ( scrollBlockHeight / contentHeight ) * scrollBlockHeight;

	if(contentHeight < scrollBlockHeight) { // if the content is short, hide the scrollbar
		$("div.scrollbar").css('display', 'none');
		$("div#scrollbar_holder").css('display', 'none');
	} else {
		$("div.scrollbar").height(scrollbarHeight)
	  }

	/* trigger 1: start function drag */
	$("div.scrollbar").draggable({
			axis: 'y',
			containment: 'parent',
			drag: function() {
				var getPositionTop 	= parseInt($(this).css('top')); // get css top
				// formula for content up
				var scrollTopNew 	= ( getPositionTop / scrollBlockHeight) * (contentHeight);
				//console.log(getPositionTop); // logs
				$("div#scroll_content").css("top", '-'+scrollTopNew+'px'); // up the content
			}
	});
	/* trigger 1: end function drag */

	/* trigger 2: function scroll */
	var getmoduloHeight = scrollBlockHeight - scrollbarHeight; // scrollBlock - scrollbar

	// get total height content
	var formulateHeight = ( getmoduloHeight / scrollBlockHeight) * (contentHeight);

	$('#scroll_block').bind("mousewheel", function (event, delta) {
		//console.log(delta); // delta scroll trigger
		var getPositionTop		= parseInt( $('div.scrollbar').css('top')); // get css top
		var scrollTopNew		= getPositionTop - (delta * 10); // with delta
		var scrollTopContent	= ( scrollTopNew / scrollBlockHeight) * (contentHeight);

		//console.log(getPositionTop);
		if(scrollTopNew < 0) { // if rich the top content, return false, and set default
			$("div.scrollbar").css("top", "0px" );
			$("div#scroll_content").css("top", "0px" );
			return false;
		}
		if(scrollTopContent > formulateHeight) { // if rich the bottom content, return false, and set default
			$("div.scrollbar").css("top", getmoduloHeight );
			$("div#scroll_content").css("top", '-'+formulateHeight+'px');
			return false;
		}

		$("div#scroll_content").css("top", '-'+scrollTopContent +'px'); // up the content
		$("div.scrollbar").css("top", scrollTopNew ); // down the scroll bar
	});
	/* trigger 2: end function scroll */

	/* trigger 3: click scrollbar holder, scroll start */
	$("div#scrollbar_holder").click(function(e) { // add event

	  	var getPositionTop 	= parseInt($("div.scrollbar").css('top')); // get css top

	  //var pageX 			= e.pageX - this.offsetLeft;
		var pageY 			= e.pageY - this.offsetTop;

		var topWithScroll 	= getPositionTop + scrollbarHeight; // get height scrolltop + scrollbar Height
		var positionTop 	= pageY - scrollbarHeight; // pagey - scrollbar Height =  to get the get height scrolltop

		//console.log(pageY);
		var pageY_adjust = (pageY - 20); // adjust
		if(pageY_adjust < getPositionTop) { // click up the scroll bar

				$("div.scrollbar").stop(true, false).animate({ "top" :   pageY-40 }, 'fast');
				var getPositionTop_click = pageY-40;

				if(getPositionTop_click < 0) { // if user click the top level of the scroll, set to animate to top

					$("div.scrollbar").stop(true, false).animate({ "top" :   0 }, 'fast');
					$("div#scroll_content").stop(true, false).animate({ "top" :   0 }, 'fast');

				} else {

					var scrollTopNew 	= ( getPositionTop_click / scrollBlockHeight) * (contentHeight);
					$("div#scroll_content").stop(true, false).animate({ "top" :   '-'+scrollTopNew+'px' }, 'fast');

					}
		} else { // click down the scroll bar
			if(pageY > topWithScroll) {

					$("div.scrollbar").stop(true, false).animate({ "top" : positionTop }, 'fast');
					var getPositionTop_click = positionTop;

					if(pageY > scrollBlockHeight) { // if user click the bottom level of the scroll, set to animate to bottom

						$("div.scrollbar").stop(true, false).animate({ "top" : getmoduloHeight }, 'fast'); // getmoduloHeight from scrollbar var
						$("div#scroll_content").stop(true, false).animate({ "top" :   '-'+formulateHeight+'px' }, 'fast');  // formulateHeight from scrollbar var

					} else {

						var scrollTopNew 	= ( getPositionTop_click / scrollBlockHeight) * (contentHeight);
						$("div#scroll_content").stop(true, false).animate({ "top" :   '-'+scrollTopNew+'px' }, 'fast');

					}
			}
		  }

	e.preventDefault(); // like return false
	});
	/* trigger 3: click scrollbar holder, scroll end */
}); // jQuery End
Finally the long custom jquery script, first things first in line 7-12, we need the get the height of div#scroll_block dynamically and set the height to the div#scrollbar_holder. Then getting the height value of div#content for the formula of scroll bar. So let’s start the triggers event.
Trigger 1: Draggable Content
In line 20-32 the div#scrollbar we apply the draggable functions comes from jquery-ui-draggable.js, while dragging the div we getting the css top value that will apply the formula for content up scrolling.
Trigger 2: Scrolling Content
The scrolling event trigger starting from line 34-61, these trigger are same in drag gable function, but we need some values to work this, first the getmoduloHeight variable are the getting the value of (scrollBlockHeight – scrollbarHeight) to use and get the total height of the content, this value will we used to prevent the scroll out of the content, these variables applied in line 48-57. The delta event is for mouse scrolling, it gets the value for scrolling and we use for content up and down function.
Trigger 3: Clicking Drag Content
Finally the click drag content, it start the line 64-114, this trigger happened if the user click the div#scrollbar_holder, it move up and down the content, we set the event in the click trigger to get the value of offsetTop, what will happened in the script if the user click below and above the scroll bar it animate the content up/down and animate the scroll bar.

4. Done

We’re done, we’re creating our own custom scroll bar using jQuery. I know some of my code are complicated to understand, but sharing ideas is a good starting to create more and ideas. Hopefully my ideas you’ll make sense.
Let’s have a look at what we’ve achieved:
  • Creating our own custom scroll bar
  • Works in cross browser platform.
  • Simple and working Vertical scroll bar.

Continue Reading...

Creating jQuery Popup Div

Jquery popup is extremely popular effect for websites, as a web developer or designer we can apply this effects very easy in our projects, we can search and download, using third party jQuery plugins. If your wonder on how to create popup div in your own hand. In this article i would like to share, on how to create a pop up div, effect using the popular jQuery library.
In this jquery example / tutorial we create jquery popup div in ‘click trigger’ event, it pop up displays with opacity background and it will remains center the popup if you scrolling zoom out the browser and closing it fadeout, and also you can customize the content of the popup div. Let’s begin.

1. Creating the Page Template

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Creating Popup Div | istockphp.com</title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script>
<script type="text/javascript" src="js/script.js"></script>
</head>

<body>
	<a href="#" class="topopup">Click Here Trigger</a>

    <div id="toPopup">

        <div class="close"></div>
       	<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
		<div id="popup_content"> <!--your content start-->
            <p>netus et malesuada fames ac turpis egestas. </p>
            <p align="center"><a href="#" class="livebox">Click Here Trigger</a></p>
        </div> <!--your content end-->

    </div> <!--toPopup end-->

	<div class="loader"></div>
   	<div id="backgroundPopup"></div>
</body>
</html>
In index.html, we include the css, jQuery and js script after the title tag; in the body we have 3 div containers for popup div event.
  • div container for loading
  • div container for popup background,
  • and div container for popup

2. The stylesheet

style.css
#backgroundPopup {
    z-index:1;
    position: fixed;
    display:none;
    height:100%;
    width:100%;
    background:#000000;
    top:0px;
    left:0px;
}
#toPopup {
    font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
    background: none repeat scroll 0 0 #FFFFFF;
    border: 10px solid #ccc;
    border-radius: 3px 3px 3px 3px;
    color: #333333;
    display: none;
    font-size: 14px;
    left: 50%;
    margin-left: -402px;
    position: fixed;
    top: 20%;
    width: 800px;
    z-index: 2;
}
div.loader {
    background: url("../img/loading.gif") no-repeat scroll 0 0 transparent;
    height: 32px;
    width: 32px;
    display: none;
    z-index: 9999;
    top: 40%;
    left: 50%;
    position: absolute;
    margin-left: -10px;
}
div.close {
    background: url("../img/closebox.png") no-repeat scroll 0 0 transparent;
    cursor: pointer;
    height: 30px;
    position: absolute;
    right: -27px;
    top: -24px;
    width: 30px;
}
span.ecs_tooltip {
    background: none repeat scroll 0 0 #000000;
    border-radius: 2px 2px 2px 2px;
    color: #FFFFFF;
    display: none;
    font-size: 11px;
    height: 16px;
    opacity: 0.7;
    padding: 4px 3px 2px 5px;
    position: absolute;
    right: -62px;
    text-align: center;
    top: -51px;
    width: 93px;
}
span.arrow {
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 7px solid #000000;
    display: block;
    height: 1px;
    left: 40px;
    position: relative;
    top: 3px;
    width: 1px;
}
div#popup_content {
    margin: 4px 7px;
    /* remove this comment if you want scroll bar
    overflow-y:scroll;
    height:200px
    */
}
In the css, if you want scrollbar in the popup just remove comment in line 74.

3. The jQuery script

script.js
jQuery(function($) {

	$("a.topopup").click(function() {
			loading(); // loading
			setTimeout(function(){ // then show popup, deley in .5 second
				loadPopup(); // function show popup
			}, 500); // .5 second
	return false;
	});

	/* event for close the popup */
	$("div.close").hover(
					function() {
						$('span.ecs_tooltip').show();
					},
					function () {
    					$('span.ecs_tooltip').hide();
  					}
				);

	$("div.close").click(function() {
		disablePopup();  // function close pop up
	});

	$(this).keyup(function(event) {
		if (event.which == 27) { // 27 is 'Ecs' in the keyboard
			disablePopup();  // function close pop up
		}
	});

        $("div#backgroundPopup").click(function() {
		disablePopup();  // function close pop up
	});

	$('a.livebox').click(function() {
		alert('Hello World!');
	return false;
	});

	 /************** start: functions. **************/
	function loading() {
		$("div.loader").show();
	}
	function closeloading() {
		$("div.loader").fadeOut('normal');
	}

	var popupStatus = 0; // set value

	function loadPopup() {
		if(popupStatus == 0) { // if value is 0, show popup
			closeloading(); // fadeout loading
			$("#toPopup").fadeIn(0500); // fadein popup div
			$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
			$("#backgroundPopup").fadeIn(0001);
			popupStatus = 1; // and set value to 1
		}
	}

	function disablePopup() {
		if(popupStatus == 1) { // if value is 1, close popup
			$("#toPopup").fadeOut("normal");
			$("#backgroundPopup").fadeOut("normal");
			popupStatus = 0;  // and set value to 0
		}
	}
	/************** end: functions. **************/
}); // jQuery End
In the click event we triggered the 'loading()' function and delay .5 second and triggered theloadPopup(), and same for close trigger, we add little more for closing the popup, if hover the ‘Close’ the tool tip message will triggered and keyboard event for close.

4. Done

Wer’e done, we learn one of jquery sample on creating our own popup div using jQuery, you can edit the content of the popup like adding text or form. Let’s have a look at what we’ve achieved:
  • We create popup div without third party plugin
  • Works in old IE browser, IE 7,8
  • We add little feature, hover tool tip and keyboard event

Continue Reading...

How To Check The Email If Already Exit

Why to use Ajax?

We use Ajax instead of plain PHP, because Ajax can able to talk the database without reloading the browser. We can send the data from the form and post the data to the request file. Some sites use Ajax in the registration form to verify the user email or username exist.

Step 1: Create a Database

First create a database named ‘email_exists’ you can change if you want, and create a table named ‘users’ and fields.
CREATE TABLE `users` (
 `first_name` varchar(50) NOT NULL,
 `last_name` varchar(50) NOT NULL,
 `email` varchar(50) NOT NULL
);

Step 2: Create Database Connection

Create file name ‘database.php’ to connect from the database we have assigning the database credentials, MySQL host, user, password and database name the ‘email_exists’.
<?php
$db = mysql_connect("localhost", "root", ""); // your host, user, password
  if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("email_exists"); // database name
  if(!$select_db) { echo mysql_error(); }
?>

Step 3: Creating the Registration Page

Create a file name ‘index.php’ our form page or home page, in home page we have a registration form the user can input ‘first name’, ‘last name’ and ‘email’ as our example in this tutorial, and also we need the validate the form using jQuery.
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check the Email if Already Exist | istockphp.com </title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" /> <!--- include the css file -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> <!--- include the live jquery library -->
<script type="text/javascript" src="js/script.js"></script> <!--- include the our jquery file  -->
</head>

<body>
	<div id="wrap"> <!--wrap start-->
    	<br />
    	<h1>Check the Email if Already Exist</h1>
         <form action="" method="post" id="mainform">
        <table id="table_data">

        	<tr>
            	<td>First Name</td>
            	<td><input name="fname" type="text" size="30"></td>
				<td><span class="fname_val validation"></span></td>
            </tr>
            <tr>
            	<td>Last Name</td>
            	<td><input name="lname" type="text" size="30"></td>
              	<td><span class="lname_val validation"></span></td>

            </tr>
            <tr>
            	<td>Email</td>
            	<td><input name="email" type="text" size="30"></td>
                <td><span class="email_val validation"></span></td>
			</tr>
            <tr>
            	<td>&nbsp;</td>
                <td><input name="register" type="button" value="Register"> <span class="loading"></span></td>
                <td></td>
            </tr>
		</table>
       </form>
	 </div> <!--wrap end-->
</body>
Below the title tag we include the stylesheet the ‘style.css’ and the live jQuery script from google cdn, and lastly the jQuery script.
style.css
body {
	font-family: Arial, Helvetica, sans-serif;
	font-size:13px;
	color:#464646
}
h1 {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    margin-left: 25px;
}
p {
	margin:10px;
	padding:10px;
	color:#000000;
}
table#table_data {
	margin-left: 25px;
}
form#mainform input[type="text"] {
    border: 1px solid #E5E5E5;
    margin-bottom: 3px;
    padding: 5px;
}
form#mainform input[name="register"] {
    border: 1px solid #BBBBBB;
    border-radius: 12px 12px 12px 12px;
    color: #464646;
    cursor: pointer;
    font-size: 13px;
    margin-top: 10px;
    padding: 3px 8px;
}
form#mainform input[name="register"]:hover {
    border: 1px solid #666666;

}
span.validation {
	font-style:italic;
	color:#B41F2B;
}
span.loading {
    font-style: italic;
    left: 5px;
    position: relative;
}

Step 4: Creating the jQuery Ajax Script

script.js
jQuery(function($) {
	var val_holder;

	$("form input[name='register']").click(function() { // triggred click

		/************** form validation **************/
		val_holder 		= 0;
		var fname 		= jQuery.trim($("form input[name='fname']").val()); // first name field
		var lname 		= jQuery.trim($("form input[name='lname']").val()); // last name field
		var email 		= jQuery.trim($("form input[name='email']").val()); // email field
		var email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // reg ex email check

		if(fname == "") {
			$("span.fname_val").html("This field is empty.");
		val_holder = 1;
		}
		if(lname == "") {
			$("span.lname_val").html("This field is empty.");
		val_holder = 1;
		}
		if(email == "") {
			$("span.email_val").html("This field is empty.");
		val_holder = 1;
		}
		if(email != "") {
			if(!email_regex.test(email)){ // if invalid email
				$("span.email_val").html("Your email is invalid.");
				val_holder = 1;
			}
		}
		if(val_holder == 1) {
			return false;
		}
		val_holder = 0;
		/************** form validation end **************/

		/************** start: email exist function and etc. **************/
		$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
		$("span.validation").html("");

		var datastring = 'fname='+ fname +'&lname='+ lname +'&email='+ email; // get data in the form manual
		//var datastring = $('form#mainform').serialize(); // or use serialize

		$.ajax({
					type: "POST", // type
					url: "check_email.php", // request file the 'check_email.php'
					data: datastring, // post the data
					success: function(responseText) { // get the response
						if(responseText == 1) { // if the response is 1
							$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
							$("span.loading").html("");
						} else { // else blank response
							if(responseText == "") {
								$("span.loading").html("<img src='images/correct.png'> You are registred.");
								$("span.validation").html("");
								$("form input[type='text']").val(''); // optional: empty the field after registration
							}
						}
					} // end success
		}); // ajax end
		/************** end: email exist function and etc. **************/
	}); // click end
}); // jquery end
In the jQuery script we create the simple validation form first for user fails to input the data. In the Ajax there are 4 parameters… type, url, data and return success.

Step 5: The Ajax Request File

<?php
require_once("database.php"); // require the db connection

/* catch the post data from ajax */
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];

$query = mysql_query("SELECT `email` FROM `users` WHERE `email` = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
	echo '1';
} else { // else not, insert to the table
	$query = mysql_query("INSERT INTO `users` (`first_name` ,`last_name` ,`email`)
							VALUES ('$fname', '$lname', '$email')");
  }

?>
We require the database connection first then, after sending the data via Ajax, we catch the post data and process to the MySQL query and send back a request and Ajax catch again the request.

Step 6: Complete

Were done, we creating the check email exist using jQuery Ajax. Let’s have a look at what we’ve achieved:
  • We’ve set up a database.
  • We’ve create a simple form registration form.
  • We’ve write the jQuery Ajax script to able to talk the database without reloading the broswer.
  • We’ve write the request file from jQuery Ajax, to get the response of PHP script.

Continue Reading...

12 Things to Do Before Applying for Google Adsense

Google Adsense is world’s larges Ads Network and works at Pay Per Click system. It’s paying rates are better than all of other networks which is the biggest reason it is so popular to all Bloggers and Webmasters. But since everybody is running behind them, they have made the approval system very strict. You make little mistakes and get disapproved every time. So you need a complete guidance and list of thing that you need to do before applying for Google Adsense and supposing that you are ready.
12 Things to Do Before Applying for Google Adsense

12 Things to Do Before Applying for Google Adsense


1. Privacy Policy :

One of the common mistakes that every Blogger makes and that I made many times before finally getting approved. Even though there are people out there who say that having a Privacy Policy for a Blog doesn’t makes sense but they are wrong.
A Privacy actually describes to your readers about what they will get on your Blog , what they should do and what they should not. So obviously there is nothing bad in having a Privacy Policy. While it can affect somehow on your Adsense Approval, you must give it a try. You can write it yourself or find Privacy Policy Generators online (You don’t need a lawyer anyway).


2. About Page

An About has major role and importance if you don’t want to apply for Adsense. But when it comes to Adsense, they are about Zero chances of getting approved if you are not showing this page.About page simply describes about you and your Blog . This will not only help you establish a relationship with readers but it will also make them trust upon you.


3. Contact Us Page

It’s quite obvious that everyone has his/her own opinion. What one of your readers likes may be bothering someone else. Than it is better to give them opportunity to speak up to you and tell how they feel about your Blog, what they want to be edited , what they liked or hated.
It will also show the Google Adsense Team that is viewing your site that you actually care about your readers and not only the money and Adsense.


4. Name/ Email Verification

Make sure to put you Name and Email address in some easily visible area like About Me and Contact Us pages. It will confirm to Google Adsense Team that it is the same person who applied for Adsense and not some spam, crappy bots.


5. Age Verification

I’m really laughing out typing this. ;)
Why?
Because this is where I encountered a problem. Instead of 18, I accidentally published my age as 17 while on Adsense Application Form, it was accurately 18.
Hence there started a problem . Because Google Adsense is not for under 18 people. I realized this problem after being disproved a few times without any legitimate reason. So I advice you to be accurate while typing your age.


6. Minimum Number of Posts

There is no exact answer. Not even one. Because I have seen very established Blogs with 400+ posts and their owner telling me that Google Adsense is rejecting them while somewhere ,people with 40,50 posts are enjoying making money. Exactly what I said that there is no actual answer. However, we can always predict things. According to my experience , you should only apply after you have more than 70 posts. Posts length should must be 500+ words too.
Read : Difference Between Short Length Post Vs Length Posts – What’s Best?


7. Design

Your Blog is the biggest thing after Content. This represents your expertise ,experience and Professionalism. So be careful because anything can kill your Chances.


8. Content Type

Be careful with what type of content you are publishing. Because it is something that truly matters. Google Adsense is not for Pornographic, Illegal Items, Drugs or other Blogs / Sites like that. Also Adsense team won’t be willing to allow you to step in if you own a Non English Blog. Having posts shorter than 300 words in length is also Red Signal.


9. Providing Value

Don’t complain about not making money and don’t clearly state that your are Blogging for Money only and have no other interest in it. Because this will show them that you will not be providing values to your readers any day. Hence another Red Light glows up.


10. Top Level Domain

12 Things to Do Before Applying for Google Adsense
Those are gone far away when Adsense used to approve “Blogspot” and “WordPress.com” Blogs. As for today, you must have your own unique domain that specifies your Blog. If you don’t have one yet, stop dreaming about getting approved with Sub domains and go buy a Top Level Domain.
Another important thing about domain is it’s age. Because for most of Asian Countries, Adsense has placed an age restriction. They don’t accept any sites before they are 6 months old.


11. Other Ad Networks

If you have any other Ads placed like Chitika, Clicksor or anything, it’s time to drop them off.
Even Google Adsense allows you to use other Ad Networks along with them, it’s better to remove the ads before Applying and don’t put them back until you get a reply from Adsense Team.


12. Paid Traffic 

Google hates the sites that are getting Paid traffic and mostly penalizes them so there is not a damn chance of getting Adsense Approval letter for a site that is getting paid traffic. You can bring traffic from Search Engines or any other way you want but if you want to earn via Google Adsense the right way, paid traffic is not a solution.

Continue Reading...

Saturday, October 19, 2013

USEFUL REGULAR EXPRESSIONS

In Web Development, there have forms we need to secure and validate using Regular Expression, in some cases are registration form, transaction forms such as valid email, valid postal code, matching strong password and securities.
In this article, i have compiled the useful of JavaScript Regular Expression, this is the most common regular expression we use in web development such validating forms. These Regular Expression will not match in common cases, it even fewer special cases you might be need, because any Regular Expression can be written broadly and narrowly, meaning, broadly is a match a lot of pattern and narrowly is very restricted in matching.

1. Matching names

Regex:
1/^([A-Z][A-Za-z.'\- ]+) (?:([A-Z][A-Za-z.'\-]+) )?([A-Z][A-Za-z.'\-]+)$/
String that matches:
1John Doe
2John de Doe
3John Doe Doe
4John Doe D. Doe J.r III
Pattern can match any valid names with first character capitalize.

2. Matching postal codes

Regex:
1/^\d{4,5}(?:-\d{4,5})?$/
String that matches:
175087
210010-6543
Pattern can match postal codes broadly, they match mostly US postal code.

3. Matching email addresses

Regex:
1/^[\w%_\-.\d]+@[\w.\-]+.[A-Za-z]{2,6}$/
String that matches:
1someone@istockphp.com
2someone@istockphp.co.uk
3someone@istockphp.net
4some-one@istockphp.edu
Pattern can match any valid email format, however this is most common use for validating email in registration form.

4. Matching urls

Regex:
1/^(http|https):\/\/[\w.\-]+(\.[\w\-]+)+[/#?\w\-.,@?^=&%:;/~\\+#]+$/
String that matches:
1http://www.istockphp.com
2 
3 
4http://istockphp.com
5 
6 
7http://blog.istockphp.com
8 
9 
10https://www.istockphp.com
11 
12 
13http://www.istockphp.com/product_page.html
14 
15 
16http://www.istockphp.com/images/image.gif
17 
18 
19http://www.istockphp.com/product/
20 
21 
22http://www.istockphp.com/product/3456
23 
24 
25http://www.istockphp.com/product_page.php?product=28
26 
27 
28http://www.istockphp.com?product=28&color=blue
29 
30 
31http://www.istockphp.com#details
32 
33 
34http://255.255.255.255
In the form, might have a extra field to input the user for URL, this regex validate the valid url.

5. Matching decimal numbers

Regex:
1/^(\d*\.\d+|\d+)$/
String that matches:
15.4
2314.35634
30.123
4.345
525
Pattern match a valid decimal numbers.

5. Matching currencies

Regex:
1/^(\$|£|¥)(\d*\.\d+|\d+)$/
String that matches:
1$50
2$43.23
3$0.39
4$.60
5£498.10
6¥12
Pattern can match the right currencies, in reg ex you can add more currencies to match.

6. Matching ip addresses

Regex:
1/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
String that matches:
1255.255.255.255
20.0.0.0
367.52.159.38
4067.052.159.038
Pattern can match the right ip address, obviously the ip address ’999.999.999.999′ will not match.

7. Matching dates

Regex:
1/^\d{1,4}[-/](0?[1-9]|1[0-2])[-/](0?[1-9]|[12][0-9]|3[01])$/
String that matches:
12000-11-15
22000-6-9
32000-06-09
42000/6/9
Pattern can matches the date format, year, month and day.

8. Matching time in 12hrs

Regex:
1/^(0?[1-9]|1[0-2]):[0-5][0-9]([aApP][mM])?/
String that matches:
102:34
22:34pm
32:34PM
402:34
512:34
612:59
71:00PM
Pattern can match 12 hrs time. it match up to 12:59 am and pm.

9. Matching time in 24hrs with Time zone

Regex:
1/^([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?( ([A-Z]{3}|GMT [-+]([0-9]|1[0-2])))?$/
String that matches:
10:02
22:34
302:34
412:34
512:34:56
612:34 EST
712:34 GMT -5
812:34 GMT +12
923:45
Pattern can match 24 hrs time. it match up to 23:59 including timezone.

10. Matching HTML tags

Regex:
1/^<(?:([A-Za-z][A-Za-z0-9]*)\b[^>]*>(?:.*?)|[A-Za-z][A-Za-z0-9]*\b[^/>]*/>)$/
String that matches:
1<strong>Bold</strong>
2<em>Emphazied</em>
3<b>Bold</b>
4<i>Italics</i>
5<span id="foo">this is the text</span></pre>
6 
7<hr />
8 
9<pre>
10<strong>Bold</strong>
11<em>Emphazied</em>
12<b>Bold</b>
13<i>Italics</i>
14<span id="foo">this is the text</span></pre>
15 
16<hr />
17 
18<pre>
Pattern can match HTML tags.

11. Validating strong passwords

Regex:
1/^(?=.*\d)(?=.*[~!@#$%^&*()_\-+=|\\{}[\]:;<>?/])(?=.*[A-Za-z])(?=.*[a-z])\S{8,15}$/
String that matches:
1mypassword69[]
2mypass';i#%^9[]
This pattern help to make sure user give a secure password that’s harder for hacker to crack it.
Pattern for password requires.
  • Password Any character, except space.
  • Password at least 8 characters long
  • And not more than 15 characters.
  • Password must have a number.
  • Password must have a special character.

12. Matching credit card numbers

Regex:
1/^(?:3[47]\d{2}([\- ]?)\d{6}\1\d{5}|(?:4\d{3}|5[1-5]\d{2}|6011)([\- ]?)\d{4}\2\d{4}\2\d{4})$/
String that matches:
1American Express
2370012345612345
33700 123456 12345
43700-123456-12345
5 
6Visa
74000123412341234
84000 1234 1234 1234
94000-1234-1234-1234
10 
11Mastercard
125100123412341234
135100 1234 1234 1234
145100-1234-1234-1234
15 
16Discover
176011123412341234
186011 1234 1234 1234
196011-1234-1234-1234
Pattern can match 4 major of credit card numbers, American Express, Visa, MasterCard, Discover.
Continue Reading...