Thursday, 27 October 2011

Game Script Using JQUERY

JavaScript code

This code will read a key Code upon pressing a key on keyboard.

$(document).keydown( function(event)
{
var keycode = event.keyCode;


Screen resolution is read by the following code. 


var width = screen.width - 100;
var height = screen.height - 200;


And next function is used to Generate a random alphabet between A - Z.
Here the key code values for A - Z are 65 - 90.
Math.random() - used to generate a random number
String.fromCharCode() - is used to convert a key Code into its equivalent Character

// Generating a random number between 65 -90
var k = Math.floor(Math.random() * ( 90 - 65 + 1 )) + 65;var ch = String.fromCharCode(k);
For css styling purpose we are generating a random color for every bubble and this is 
done by the following function
// Generating a random color
function randomColor(){
var color = '';
var values = ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
for (c = 0; c < 6; c++) {
no = Math.floor(Math.random() * 15);
color += values[no];
}
return color;
}
});

Final Javascript Code
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Getting screen resolutions and positioning the start button
var width = screen.width - 100;
var height = screen.height - 200;
var code = 0;
$('#start').css(
"top" : (height/2)+'px',
"left" : (width/2)+'px'
});

$('#start').click( function()
{
$(this).fadeOut('slow');
$('#score').show();
genLetter();
});

// Dealing KeyEvents and fading out matched bubble
$(document).keydown( function(event)
{
var keycode = event.keyCode;
$('.bubb'+keycode).animate(
{
"top" : height+"px", "opacity" : 0
}, 'slow');

$('.bubb'+keycode).fadeOut('slow').hide( 'slow', function()
{
code += 20;
$('#score').html(code);
$(this).remove();
}
);
});

// Generating a random alphabet between A-Z
function genLetter()
{
var color = randomColor();
var k = Math.floor(Math.random() * ( 90 - 65 + 1 )) + 65;
var ch = String.fromCharCode(k);
var top = Math.floor(Math.random() * height );
var left = Math.floor(Math.random() * width );
$('body').append('<span class="bubb bubb'+ k +'" style="left: '+ left +'; top: '+ top +'; background-color:'+ color +'">'+ ch +'</span>');
setTimeout(genLetter, 1000);
}
// Generating a random color
function randomColor()
{
var color = '';
var values = ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
for (c = 0; c < 6; c++)
{
no = Math.floor(Math.random() * 15);
color += values[no];
}
return color;
}
});
</script>

HTML Code

<body>
<div id="score">0</div>
<div id="start">Start</div></body>



CSSbody

{
width: 100%;
margin: 0 auto;
padding: 0;
}

.bubb
{
position: absolute;
width:30px;
height: 30px;
font: bold 14px verdana;
background-color: yellow;
text-align: center;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
vertical-align: middle;
padding: 5px;
}

#score
{
font-size:46px;
top: 25px;
right: 50px;
display: none;
text-align:right;
}

#start
{
width: 50px;
padding: 10px 15px;
text-align: center;
font:bold 15px arial;
background-color: #dedede;
color: #000;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
position: absolute;
}

#start:hover
{
cursor: pointer;
}

Wednesday, 26 October 2011

Creating Login_Register page Using OOPS in PHP

The Root folder like:


OOP_sample
                 =>include (folder)
                             =>config.php
                             =>functions.php
                =>register.php
                =>login.php
                =>home.php
config.php


<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'admin1234');
define('DB_DATABASE', 'test');
class DB_Class {
function __construct() {
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD)
or die('Oops Sql connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection) or
die('Database error -> ' . mysql_error());
}


}
?>

functions.php


<?php
include_once 'config.php';
class User {
public function __construct()
{
$db = new DB_Class();
}
public function register_user($name, $username, $password, $email)
{
$password = md5($password);

$sql = mysql_query("SELECT uid from users WHERE username = '$username'
or email = '$email'");
$no_rows = mysql_num_rows($sql);

if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name,
email)
values
('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}

}
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername'
or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);

if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return TRUE;
}
else
{
return FALSE;
}
}
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
public function get_session()
{
return $_SESSION['login'];
}
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>


login.php


<?php
session_start();
include_once 'include/functions.php';
$user = new User();
if ($user->get_session())
{
header("location:home.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$login = $user->check_login($_POST['emailusername'], $_POST['password']);
if ($login) {
// Registration Success
header("location:login.php");
} else {
// Registration Failed
echo 'Username / password wrong';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<style>
body
{
font-family:Arial, Helvetica, sans-serif;
}
</style>
<script language="javascript" type="text/javascript">
function submitregistration() {
var form = document.login;
if(form.emailusername.value == "")
{
alert( "Enter email or username." );
return false;
}
else if(form.password.value == "")
{
alert( "Enter password." );
return false;
}


}



</script>
</head>
<body>
<div id="container">

<div id="main-body">
<br/><br/>
<form method="POST" action="" id="login_form" name="login">
<div class="head">
<b> Login Here !</b><br/><br/>
</div>
<label>Email or Username</label><br/>
<input type="text" name="emailusername" required="true"/><br/> <br/>
<label>Password</label><br/>
<input type="password" name="password" id="password"
required="true"/><br/><br/>
<input type="hidden" name="flag" value="login"/>
<input type="submit" name="login_btn" onclick="return( submitregistration());"
value="Login"/><br/><br/>
<label><a href="register.php">Register new user</a></label>
</form>

</div>

</div>
</body>
</html>


register.php


<?php


include_once 'include/functions.php';
$user = new User();


// Checking for user logged in or not
if (!$user->get_session())
{
header("location:login.php");
}


if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$register = $user->register_user($_POST['name'], $_POST['username'], $_POST['password'], $_POST['email']);
if ($register) {
// Registration Success
echo 'Registration successful <a href="login.php">Click here</a> to login';
} else {
// Registration Failed
echo 'Registration failed. Email or Username already exits please try again';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<style>
body
{
font-family:Arial, Helvetica, sans-serif;
}
</style>
<script language="javascript" type="text/javascript">


function submitregistration() {
var form = document.reg;
if(form.name.value == "")
{
alert( "Enter name." );
return false;
}
else if(form.username.value == "")
{
alert( "Enter username." );
return false;
}
else if(form.password.value == "")
{
alert( "Enter password." );
return false;
}
else if(form.email.value == "")
{
alert( "Enter email." );
return false;
}


}
</script>
</head>
<body>
<div id="container">
<div id="main-body">
<br/><br/>
<form method="POST" action="register.php" id="register_form" name="reg">
<div class="head">
<b> I am new user !</b><br/><br/>
</div>
<label>Full Name</label><br/>
<input type="text" name="name" required="true"/><br/><br/>
<label>Username</label><br/>
<input type="text" name="username" required="true"/><br/><br/>
<label>Password</label><br/>
<input type="password" name="password" required="true"/><br/><br/>
<label>Email</label><br/>
<input type="text" name="email" id="email" required="true"/><br/><br/>
<input type="submit" name="register_btn" onclick="return( submitregistration());"
value="Register"/><br/><br/>
<label><a href="login.php">I already Registered. Login here</a></label>
</form>
</div>
</div>
</body>
</html>

home.php


<?php
session_start();
include_once 'include/functions.php';
$user = new User();
$uid = $_SESSION['uid'];
if (!$user->get_session())
{
header("location:login.php");
}
if ($_GET['q'] == 'logout')
{
$user->user_logout();
header("location:login.php");
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<style>
body
{
font-family:Arial, Helvetica, sans-serif;
}
h1
{
font-family:'Georgia', Times New Roman, Times, serif;
}
</style>
</head>
<body>
<div id="container">
<div id="header">
<a href="?q=logout">LOGOUT</a>
</div>
<div id="main-body">
<br/><br/><br/><br/>
<h1>
Hello <?php $user->get_fullname($uid); ?>
</h1>
</div>
<div id="footer"></div>
</div>
</body>
</html>

Tuesday, 25 October 2011

Geo Location Script Using JQUERY

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/
1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
function success(position)
{
var s = document.querySelector('#status');
if (s.className == 'success')
{
return;
}
s.innerHTML = "Found you!";
s.className = 'Success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '100%';
mapcanvas.style.width = '100%';
document.querySelector('#map').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here!"
});
$.cookie("MyLat", position.coords.latitude); // latitude value stores here
$.cookie("MyLon", position.coords.longitude); //longitude value stores here
}
function error(msg)
{
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'Fail';
}
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(success, error);
}
else
{
error('Not supported'); //HTML Support
}

//Jquery Code
$(document).ready(function()
{
$("#check").click(function()
{
var lat = $.cookie("MyLat");
var lon = $.cookie("MyLon");
alert('Latitued: '+lat);
alert('Longitude: '+lon);
var url="http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false";
alert('Google Map API: '+url);
//Get Json Request Here
});
});
</script>
//HTML Code
<input type='button' id='check' value='Check-out'/>
<div id="status">Loading.............</div>
<div id="map"></div>

Monday, 24 October 2011

Base64 Encoding and decoding in Javascript and php



Encode and decode base64 in PHP


<?php
$str = '796';
echo base64_encode($str);
?>


<?php
$str = 'ckz2';
echo base64_decode($str);
?>


In JavaScript

<html>
 <head>
    <title>base64 Encoding/Decoding</title>
 </head>
 
 <script type="text/javascript">
 <!--
 
 var keyStr = "ABCDEFGHIJKLMNOP" +
              "QRSTUVWXYZabcdef" +
              "ghijklmnopqrstuv" +
              "wxyz0123456789+/" +
              "=";
 
 function encode64(input) {
    input = escape(input);
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
 
    do {
       chr1 = input.charCodeAt(i++);
       chr2 = input.charCodeAt(i++);
       chr3 = input.charCodeAt(i++);
 
       enc1 = chr1 >> 2;
       enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
       enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
       enc4 = chr3 & 63;
 
       if (isNaN(chr2)) {
          enc3 = enc4 = 64;
       } else if (isNaN(chr3)) {
          enc4 = 64;
       }
 
       output = output +
          keyStr.charAt(enc1) +
          keyStr.charAt(enc2) +
          keyStr.charAt(enc3) +
          keyStr.charAt(enc4);
       chr1 = chr2 = chr3 = "";
       enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);
 
    return output;
 }
 
 function decode64(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
 
    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    if (base64test.exec(input)) {
       alert("There were invalid base64 characters in the input text.\n" +
             "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n"                           
                                   +
             "Expect errors in decoding.");
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
    do {
       enc1 = keyStr.indexOf(input.charAt(i++));
       enc2 = keyStr.indexOf(input.charAt(i++));
       enc3 = keyStr.indexOf(input.charAt(i++));
       enc4 = keyStr.indexOf(input.charAt(i++));
 
       chr1 = (enc1 << 2) | (enc2 >> 4);
       chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
       chr3 = ((enc3 & 3) << 6) | enc4;
 
       output = output + String.fromCharCode(chr1);
 
       if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
       }
       if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
       }
 
       chr1 = chr2 = chr3 = "";
       enc1 = enc2 = enc3 = enc4 = "";
 
    } while (i < input.length);
 
    return unescape(output);
 }
 
 //--></script>
 
 <body>
 
    <form name="base64Form">
 
       Type in the message you want to encode in base64, or paste<br>
       base64 encoded text into the text field, select Encode or Decode, <br>
       and click the button!<br>
 
       <textarea name="theText" cols="40" rows="6"></textarea><br>
 
       <input type="button" name="encode" value="Encode to base64"
          onClick="document.base64Form.theText.value=encode64
           (document.base64Form.theText.value);">
 
       <input type="button" name="decode" value="Decode from base64"
                              onClick="document.base64Form.theText.value=decode64
                                        (document.base64Form.theText.value);">
 
    </form>
 
 </body>
</html>

Saturday, 22 October 2011

Validate a FORM from both clientside and serverside


Here I will explain step by step


Step 1:

First approach to the xHTML Layout
In this case we will create a simple HTML layout showing our form. In a first approach the HTML will look like this:

view plaincopy to clipboardprint?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>yensdesign.com - Validate Forms using PHP and jQuery</title>
    <link rel="stylesheet" href="css/general.css" type="text/css" media="screen" />
</head>
<body>
    <a id="logo" title="Go to yensdesign.com!" href="http://www.yensdesign.com"><img src="css/images/logo.jpg" alt="yensdesign.com" /></a>
    <div id="container">
        <h1>Registration process</h1>
            <div id="error">
                <ul>
                    <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li>
                    <li><strong>Invalid E-mail:</strong> Stop cowboy! Type a valid e-mail please :P</li>
                    <li><strong>Passwords are invalid:</strong> Passwords doesn't match or are invalid!</li>
                    <li><strong>Ivalid message:</strong> Type a message with at least with 10 letters</li>
                </ul>
            </div>
            <div id="error" class="valid">
                <ul>
                    <li><strong>Congratulations!</strong> All fields are OK ;)</li>
                </ul>
            </div>

        <form method="post" id="customForm" action="">
            <div>
                <label for="name">Name</label>
                <input id="name" name="name" type="text" />
                <span id="nameInfo">What's your name?</span>
            </div>
            <div>
                <label for="email">E-mail</label>
                <input id="email" name="email" type="text" />
                <span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
            </div>
            <div>
                <label for="pass1">Password</label>
                <input id="pass1" name="pass1" type="password" />
                <span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
            </div>
            <div>
                <label for="pass2">Confirm Password</label>
                <input id="pass2" name="pass2" type="password" />
                <span id="pass2Info">Confirm password</span>
            </div>
            <div>
                <label for="message">Message</label>
                <textarea id="message" name="message" cols="" rows=""></textarea>
            </div>
            <div>
                <input id="send" name="send" type="submit" value="Send" />
            </div>
        </form>
    </div>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="validation.js"></script>
</body>
</html>

As you can see we have created all divisions that will appear (or not) in our tutorial. Some of these divisions won’t be visible as default, but we will add some conditionals in PHP and CSS to get this. So these are the divisions:

#container: contains all divisions
#error: contains a list of possible errors after submitting the form
#error.valid: contains the “congratulations phrase” if all it’s OK
#customForm: contains our form
So now we have our xHTML layout ready let’s add some style with CSS.


Step 2:

Adding style with CSS
It will be fast guys, just take a look at the general.css code:


view plaincopy to clipboardprint?
@CHARSET "UTF-8";

/******* GENERAL RESET *******/  
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em,
font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody,
 tfoot, thead, tr, th, td {
border:0pt none;
font-family:inherit;
font-size: 100%;
font-style:inherit;
font-weight:inherit;
margin:0pt;
padding:0pt;
vertical-align:baseline;
}
body{
    background: #fff;
    line-height:14px;
    font-size: 12px;
    font-family: Arial,  Verdana, Helvetica, sans-serif;
    margin:0pt;
    cursor:default;
    overflow: hidden;
}
html,body{
    height:100%;
    text-align: center;
}
.clear{
    clear: both;
    height: 0;
    visibility: hidden;
    display: block;
}
a{
    text-decoration: none;
}
strong{
    font-weight: 700;
}
/******* GENERAL RESET *******/  
h1{
    font-weight: 700;
    font-size: 18px;
    line-height: 1.2em;
    border-bottom: 1px dotted #6b9ef1;
    color: #5f95ef;
    margin-bottom: 1em;
}
/******* LOGO *******/  
#logo{
    margin-top: 1em;
    display: block;
}
/******* /LOGO  *******/  
/******* CONTAINER *******/  
#container{
    width: 600px;
    margin: 40px auto;
    text-align: left;
}
/******* /CONTAINER *******/  
/******* FORM *******/  
#customForm{
    padding: 0 10px 10px;
}
#customForm label{
    display: block;
    color: #797979;
    font-weight: 700;
    line-height: 1.4em;
}
#customForm input{
    width: 220px;
    padding: 6px;
    color: #949494;
    font-family: Arial,  Verdana, Helvetica, sans-serif;
    font-size: 11px;
    border: 1px solid #cecece;
}
#customForm input.error{
    background: #f8dbdb;
    border-color: #e77776;
}
#customForm textarea{
    width: 550px;
    height: 80px;
    padding: 6px;
    color: #adaeae;
    font-family: Arial,  Verdana, Helvetica, sans-serif;
    font-style: italic;
    font-size: 12px;
    border: 1px solid #cecece;
}
#customForm textarea.error{
    background: #f8dbdb;
    border-color: #e77776;
}
#customForm div{
    margin-bottom: 15px;
}
#customForm div span{
    margin-left: 10px;
    color: #b1b1b1;
    font-size: 11px;
    font-style: italic;
}
#customForm div span.error{
    color: #e46c6e;
}
#customForm #send{
    background: #6f9ff1;
    color: #fff;
    font-weight: 700;
    font-style: normal;
    border: 0;
    cursor: pointer;
}
#customForm #send:hover{
    background: #79a7f1;
}
#error{
    margin-bottom: 20px;
    border: 1px solid #efefef;
}
#error ul{
    list-style: square;
    padding: 5px;
    font-size: 11px;
}
#error ul li{
    list-style-position: inside;
    line-height: 1.6em;
}
#error ul li strong{
    color: #e46c6d;
}
#error.valid ul li strong{
    color: #93d72e;
}
/******* /FORM *******/  

As always we make use of our cool CSS reset snippet and add some interesting parts to the specific tutorial.


Just notice that we have defined some .error classes that we will use in the jQuery part to make our tutorial a little more cool and friendly user  


Next part, the javascript validation!


Step 3:

Validation in the client side with jQuery
Yeah guys, because it could not be otherwise we will use jQuery to make the validation part in the client side. We will add / remove some .error classes to make our form a little more intuitive for the final user.


So first of all, remember that all the following code will be in the $(document).ready() of jQuery and all will be a part of the javascript file named validation.js (original, uh?).


So let’s save references to some DOM elements that we will often:


view plaincopy to clipboardprint?


//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");

As you may notice, all references are form related.


Now let’s define our validation functions that will help us in the validation process:

validateEmail(): we only allow valid emails!
validateName(): we only allow names with more than 3 letters
validatePass1(): we only allow passwords with at least 5 characters
validatePass2(): we only allow it if passwords are equal
validateMessage(): we only messages with more than 10 letters


view plaincopy to clipboardprint?
function validateName(){
    //if it's NOT valid
    if(name.val().length < 4){
        name.addClass("error");
        nameInfo.text("We want names with more than 3 letters!");
        nameInfo.addClass("error");
        return false;
    }
    //if it's valid
    else{
        name.removeClass("error");
        nameInfo.text("What's your name?");
        nameInfo.removeClass("error");
        return true;
    }
}
function validatePass1(){
    var a = $("#password1");
    var b = $("#password2");

    //it's NOT valid
    if(pass1.val().length <5){
        pass1.addClass("error");
        pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
        pass1Info.addClass("error");
        return false;
    }
    //it's valid
    else{
        pass1.removeClass("error");
        pass1Info.text("At least 5 characters: letters, numbers and '_'");
        pass1Info.removeClass("error");
        validatePass2();
        return true;
    }
}
function validatePass2(){
    var a = $("#password1");
    var b = $("#password2");
    //are NOT valid
    if( pass1.val() != pass2.val() ){
        pass2.addClass("error");
        pass2Info.text("Passwords doesn't match!");
        pass2Info.addClass("error");
        return false;
    }
    //are valid
    else{
        pass2.removeClass("error");
        pass2Info.text("Confirm password");
        pass2Info.removeClass("error");
        return true;
    }
}
function validateMessage(){
    //it's NOT valid
    if(message.val().length < 10){
        message.addClass("error");
        return false;
    }
    //it's valid
    else{
        message.removeClass("error");
        return true;
    }
}

As you can see, we are adding and removing .error classes and changing text values if needed to show the user what fields are wrong.


Now we have defined all validation functions, we only need to manage events. Here you have what we are going to do:

Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event.
Therefore the code would be:

view plaincopy to clipboardprint?
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
    if(validateName() &amp;amp; validateEmail() &amp;amp; validatePass1() &amp;amp; validatePass2() &amp;amp; validateMessage())
        return true
    else
        return false;
});

As you can see, it’s very easy to control whatever we want by using jQuery and some functions. So now that we have done the cliend site, let’s move to the server side!


Step 4: 

Validation in the server side with PHP
Now that we have the client side done, let’s use the power of PHP to complete our tutorial.


Some of you may think that we don’t need the server side validation but it’s a big error thinking about it. Remember that we can’t trust in the client side. In example: users can disable javascript in their browsers and send us undesired values.


So first of all we must create a new .php file named validation.php that will contains our validation functions written in PHP:


view plaincopy to clipboardprint?


<?php
    function validateName($name){
        //if it's NOT valid
        if(strlen($name) < 4)
            return false;
        //if it's valid
        else
            return true;
    }
    function validateEmail($email){
        return ereg("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$", $email);
    }
    function validatePasswords($pass1, $pass2) {
        //if DOESN'T MATCH
        if(strpos($pass1, ' ') !== false)
            return false;
        //if are valid
        return $pass1 == $pass2 &amp;amp;&amp;amp; strlen($pass1) > 5;
    }
    function validateMessage($message){
        //if it's NOT valid
        if(strlen($message) < 10)
            return false;
        //if it's valid
        else
            return true;
    }
?>

As you can see we have defined 4 functions:

validateName(): checks if name has at least 4 letters
validateEmail(): checks if email is valid
validatePasswords(): checks if passwords are equal and have at least 5 letters
validateMessage(): checks if message has at least 10 letters


It’s almost done guys, we only need to add some conditionals to our index.php. If you remember, we said that we are going to add some conditionals in the PHP, so it’s time to do that:


We will display #error division only if there are at least one error.
We will display #error.valid division only if all fields are OK.
So here you have the final index.php layout:


view plaincopy to clipboardprint?
<?php
    require_once("validation.php");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>yensdesign.com - Validate Forms using PHP and jQuery</title>
    <link rel="stylesheet" href="css/general.css" type="text/css" media="screen" />
</head>
<body>
    <a id="logo" title="Go to yensdesign.com!" href="http://www.yensdesign.com"><img src="css/images/logo.jpg" alt="yensdesign.com" /></a>
    <div id="container">
        <h1>Registration process</h1>

        <?if( isset($_POST['send']) &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; (!validateName($_POST['name']) || !validateEmail($_POST['email']) || !validatePasswords($_POST['pass1'], $_POST['pass2']) || !validateMessage($_POST['message']) ) ):?>
                <div id="error">
                    <ul>
                        <?if(!validateName($_POST['name'])):?>
                            <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li>
                        <?endif?>
                        <?if(!validateEmail($_POST['email'])):?>
                            <li><strong>Invalid E-mail:</strong> Stop cowboy! Type a valid e-mail please :P</li>
                        <?endif?>
                        <?if(!validatePasswords($_POST['pass1'], $_POST['pass2'])):?>
                            <li><strong>Passwords are invalid:</strong> Passwords doesn't match or are invalid!</li>
                        <?endif?>
                        <?if(!validateMessage($_POST['message'])):?>
                            <li><strong>Ivalid message:</strong> Type a message with at least with 10 letters</li>
                        <?endif?>
                    </ul>
                </div>
            <?elseif(isset($_POST['send'])):?>
                <div id="error" class="valid">
                    <ul>
                        <li><strong>Congratulations!</strong> All fields are OK ;)</li>
                    </ul>
                </div>
        <?endif?>

        <form method="post" id="customForm" action="">
            <div>
                <label for="name">Name</label>
                <input id="name" name="name" type="text" />
                <span id="nameInfo">What's your name?</span>
            </div>
            <div>
                <label for="email">E-mail</label>
                <input id="email" name="email" type="text" />
                <span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
            </div>
            <div>
                <label for="pass1">Password</label>
                <input id="pass1" name="pass1" type="password" />
                <span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
            </div>
            <div>
                <label for="pass2">Confirm Password</label>
                <input id="pass2" name="pass2" type="password" />
                <span id="pass2Info">Confirm password</span>
            </div>
            <div>
                <label for="message">Message</label>
                <textarea id="message" name="message" cols="" rows=""></textarea>
            </div>
            <div>
                <input id="send" name="send" type="submit" value="Send" />
            </div>
        </form>
    </div>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="validation.js"></script>
</body>
</html>

Friday, 21 October 2011

Edit Delete Pages using JQUERY


Database


Sample database products table columns pid, name, category, price and discount.

CREATE TABLE products
(
pid INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(70),
category VARCHAR(100),
price INT,
discount INT
);
This post contains a folder called EditDeletePage with PHP and Javascript files.

index.php
table_data.php
load_data.php
live_edit_table.php
delete_ajax.php
db.php
EditDeletePage.js



Modifications

table_edit.php

Contains table data loop. If you want to display new record for example forth record you have to follow below code standard.

<?php
$query_pag_data = "SELECT pid,name,category,price,discount from products LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$finaldata = "";
// Table Header
$tablehead="<tr><th>Product Name</th><th>Category</th><th>Price</th><th>Discount</th><th>Edit</th></tr>";
// Table Data Loop
while($row = mysql_fetch_array($result_pag_data))
{
$id=$row['pid'];
$name=htmlentities($row['name']);
$category=htmlentities($row['category']);
$price=htmlentities($row['price']);
$discount=htmlentities($row['discount']);
$tabledata.="<tr id='$id' class='edit_tr'>
<td class='edit_td' >
<span id='one_$id' class='text'>$name</span>
<input type='text' value='$name' class='editbox' id='one_input_$id' />
</td>
<td class='edit_td' >
<span id='two_$id' class='text'>$category</span>
<input type='text' value='$category' class='editbox' id='two_input_$id'/>
</td>
<td class='edit_td' >
<span id='three_$id' class='text'>$price $</span>
<input type='text' value='$price' class='editbox' id='three_input_$id'/>
</td>
// New record
<td class='edit_td' >
<span id='four_$id' class='text'>$discount $</span>
<input type='text' value='$discount' class='editbox' id='four_input_$id'/>
</td>
<td><a href='#' class='delete' id='$id'> X </a></td>
</tr>";
}
// Loop End
$finaldata = "<table width='100%'>". $tablehead . $tabledata ."</table>";
/* Total Count for Pagination */
$query_pag_num = "SELECT COUNT(*) AS count FROM products";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
?>





EditDeletePage.js

Contains Javascript.

$(".edit_tr").live('click',function()
{
var ID=$(this).attr('id');
$("#one_"+ID).hide();
$("#two_"+ID).hide();
$("#three_"+ID).hide();
$("#four_"+ID).hide();//New record
$("#one_input_"+ID).show();
$("#two_input_"+ID).show();
$("#three_input_"+ID).show();
$("#four_input_"+ID).show();//New record
}).live('change',function(e)
{
var ID=$(this).attr('id');
var one_val=$("#one_input_"+ID).val();
var two_val=$("#two_input_"+ID).val();
var three_val=$("#three_input_"+ID).val();
var four_val=$("#four_input_"+ID).val();//New record
var dataString = 'id='+ ID +'&name='+one_val+'&category='+two_val+'&price='+
three_val+'&discount='+four_val;
if(one_val.length>0&& two_val.length>0 && three_val.length>0 &&four_val.length>0)
{
$.ajax({
type: "POST",
url: "live_edit_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
$("#one_"+ID).html(one_val);
$("#two_"+ID).html(two_val);
$("#three_"+ID).html(three_val);
$("#four_"+ID).html(four_val);//New record
e.stopImmediatePropagation();
}
});
}
else
{
alert('Enter something.');
}
});






db.php

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "srinivas";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>


delete_ajax.php

<?php
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$sql = "delete from products where pid='$id'";
mysql_query($sql);
}
?>


index.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Live Edit, Pagination and Delete Records with Jquery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="EditDeletePage.js"></script>
<style type="text/css">
body{
width: 800px;
margin: 0 auto;
padding: 0;
font-family:Arial, Helvetica, sans-serif
}
#loading{
width: 100%;
position: absolute;
top: 100px;
left: 100px;
margin-top:200px;
}
#container .pagination ul li.inactive,
#container .pagination ul li.inactive:hover{
background-color:#ededed;
color:#bababa;
border:1px solid #bababa;
cursor: default;
}
#container .data ul li{
list-style: none;
font-family: verdana;
margin: 5px 0 5px 0;
color: #000;
font-size: 13px;
}
#container .pagination{
width: 800px;
height: 25px;
}
#container .pagination ul li{
list-style: none;
float: left;
border: 1px solid #006699;
padding: 2px 6px 2px 6px;
margin: 0 3px 0 3px;
font-family: arial;
font-size: 14px;
color: #006699;
font-weight: bold;
background-color: #f2f2f2;
}
#container .pagination ul li:hover{
color: #fff;
background-color: #006699;
cursor: pointer;
}
.go_button
{
background-color:#f2f2f2;border:1px solid #006699;color:#cc0000;padding:2px 6px 2px 6px;cursor:pointer;position:absolute;margin-top:-1px;
}
.total
{
float:right;font-family:arial;color:#999;
}
.editbox
{
display:none;
}
td, th
{
width:20%;
text-align:left;;
padding:5px;
}
.editbox
{
padding:4px;
}
</style>
</head>
<body>
<body>
<h1>Pagination, Live Edit and Delete Records with Jquery</h1>
Tutorial Link <a href="http://www.9lessons.info/">Click Here</a> with database ajax connection.<br><br>
<div id="loading"></div>
<div id="container"></div>
<div style="margin-top:30px">
<span style="color:#cc0000">Note</span>: Demo no database connectivity
</div>
</body>
</html>




live_edit_ajax.php


<?php
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$name=mysql_escape_String($_POST['name']);
$category=mysql_escape_String($_POST['category']);
$price=mysql_escape_String($_POST['price']);
$discount=mysql_escape_String($_POST['discount']);
$sql = "update products set name='$name',category='$category',price='$price',discount='$discount' where pid='$id'";
mysql_query($sql);
}
?>


load_data.php

<?php
include "db.php";
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 5; // Per page
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include('table_data.php');
/* ---------------Calculating the starting and endign values for the loop----------------------------------- */
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
/* ----------------------------------------------------------------------------------------------------------- */
$finaldata .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$finaldata .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$finaldata .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$finaldata .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$finaldata .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$finaldata .= "<li p='$i' style='color:#fff;background-color:#006699;' class='active'>{$i}</li>";
else
$finaldata .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$finaldata .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$finaldata .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$finaldata .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$finaldata .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$goto = "<input type='text' class='goto' size='1' style='margin-top:-1px;margin-left:60px;'/><input type='button' id='go_btn' class='go_button' value='Go'/>";
$total_string = "<span class='total' a='$no_of_paginations'>Page <b>" . $cur_page . "</b> of <b>$no_of_paginations</b></span>";
$finaldata = $finaldata . "</ul>" . $goto . $total_string . "</div>"; // Content for pagination
echo $finaldata;
}


table_data.php

<?php
$query_pag_data = "SELECT pid,name,category,price,discount from products LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$finaldata = "";
$tablehead="<tr><th>Product Name</th><th>Category</th><th>Price</th><th>Discount</th><th>Edit</th></tr>";
while($row = mysql_fetch_array($result_pag_data))
{
$id=$row['pid'];
$name=htmlentities($row['name']);
$category=htmlentities($row['category']);
$price=htmlentities($row['price']);
$discount=htmlentities($row['discount']);
$tabledata.="<tr id='$id' class='edit_tr'>
<td class='edit_td' >
<span id='one_$id' class='text'>$name</span>
<input type='text' value='$name' class='editbox' id='one_input_$id' />
</td>
<td class='edit_td' >
<span id='two_$id' class='text'>$category</span>
<input type='text' value='$category' class='editbox' id='two_input_$id'/>
</td>
<td class='edit_td' >
<span id='three_$id' class='text'>$price $</span>
<input type='text' value='$price' class='editbox' id='three_input_$id'/>
</td>
<td class='edit_td' >
<span id='four_$id' class='text'>$discount $</span>
<input type='text' value='$discount' class='editbox' id='four_input_$id'/>
</td>
<td><a href='#' class='delete' id='$id'> X </a></td>
</tr>";
}
$finaldata = "<table width='100%'>". $tablehead . $tabledata . "</table>"; // Content for Data
/* Total Count */
$query_pag_num = "SELECT COUNT(*) AS count FROM products";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
?>


Visual comparison of the two methods, creating a simple table.

Option 1, using PHP: // PHP $html = '<table>' ;     foreach ( $data as $row ) {     $html .= '<tr>...