Jul 25, 2012

AJAX Contact Form With Validation

Today I am going to share a simple tutorial on How to make a AJAX contact form with validation.

JQUERY-AJAX



What is AJAX?
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


The flow of the form is :


AJAX Process Diagram

So here I am using twitter bootstrap, so files which we need are :-

  • data.php - (here we will write our PHP code)

  • script.js - (here we will write our ajax jquery code)

  • validate.js - (jqueryvalidation plugin)

  • index.php and style.css



So the fields of our form will be Name, Email, Number, City, Area, Message, Submit

Here our city and area will also be using AJAX i.e. on city change area will also be changed.

index.php


[html]
<?php require_once('data.php'); ?>
<div class="hero-unit">
<h2>Contact Us</h2>

<form id="contactUs" name="contactUs" onsubmit="return false;">


<table cellspacing="5" cellpadding="5">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" value="" name="name" id="name" class="required name"/></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" value="" name="email" id="email" class="required email"/></td>
</tr>
<tr>
<td><label for="number">Contact Number:</label></td>
<td><input type="text" value="" name="number" id="number" class="required number" minlength="8"/></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td>
<select id="city" name="city" onchange="javascript:changeArea('#city', '#area');">
<option value="Any">Any</option>
<?php echo getCities();?>
</select>
</td>
</tr>
<tr>
<td><label for="area">Area:</label></td>
<td><select id="area" name="area" disabled="disabled"></select></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" class="required"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="contactFormSubmit" value="Yes" />
<input type="submit" value="Submit" class="btn" onclick="javascript:formSubmit('#contactUs','#responseText');"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<div id="responseText"></div>
</td>
</tr>

</form>
</div>
[/html]



Here we just made a simple html structure of form inside a table.

To make a field mandatory, just add class="required" to input.

If you want to validate it with only email or number then add class="required email" or class="required number"

If I add a attribute minlength="8" to the number field then that field should contain at least 8 digits of number.

data.php


[php]
<?php
$cities = array('1'=>'Mumbai',
'2'=>'Chennai',
'3'=>'Noida',
'4'=>'Bangalore');

$areas = array( 'Airoli' => '1',
'Andheri' => '1',
'Bandra' => '1',
'Bhandup' => '1',
'Bhayandar' => '1',
'Boisar' => '1',
'Borivali' => '1',
'Chembur' => '1',
'Gopalapuram' => '2',
'Mount Road' => '2',
'Noida Expressway' => '3',
'Sector 1' => '3',
' Sector 128' => '3',
'Sector 129' => '3',
'Yamuna Expressway' => '3',
'Anekal ' => '4',
'Banashankari ' => '4',
'Banasvadi ' => '4',
'Banaswadi ' => '4',
'Begur ' => '4',
'Bellary Road ' => '4',
'Dobespet ' => '4',
'Electronics City' => '4');


if(isset($_REQUEST['cityID']) && $_REQUEST['cityID'] != 'Any'){

getAreas($_REQUEST['cityID']);

}

if(isset($_REQUEST['contactFormSubmit'])){
if(!isValidEmail($_REQUEST['email'])){
echo 'Enter a valid email ID';
}elseif(!is_mobileNumber($_REQUEST['number'])){
echo 'Enter a valid number';
}elseif($_REQUEST['name'] == '' || $_REQUEST['message'] == ''){
echo 'Enter valid name or message';
}else{
?>
<p><b>Thank you for contacting us, your given information : </b></p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td>Name:</td>
<td><?php echo $_REQUEST['name']?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $_REQUEST['email']?></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><?php echo $_REQUEST['number']?></td>
</tr>
<tr>
<td>City:</td>
<td><?php echo $_REQUEST['city']?></td>
</tr>

<?php if(isset($_REQUEST['area'])) : ?>
<tr>
<td>Area:</td>
<td><?php echo $_REQUEST['area']?></td>
</tr>
<?php endif; ?>

<tr>
<td>Message:</td>
<td><?php echo $_REQUEST['message']?></td>
</tr>
</table>
<?php
}
}



function getCities(){
global $cities;
foreach($cities as $Idx => $city){

echo '<option value="'.$Idx.'">'.$city.'</option>';

}
}

function getAreas($cityID = ''){
global $areas;
foreach($areas as $area => $Idx){

if($Idx == $cityID){

echo '<option value="'.$Idx.'">'.$area.'</option>';

}

}
}

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

function is_mobileNumber($mobile) {
$regex1 = '123456789';
$regex2 = '1234567890';
$regex3 = '0123456789';

if(preg_match('/^([0-9])\1*$/', $mobile)){
return false;
}elseif($mobile == $regex1){
return false;
}elseif($mobile == $regex2){
return false;
}elseif($mobile == $regex3){
return false;
}elseif(preg_match("/[^0-9]/", $mobile)){
return false;
}else{
return true;
}
}
?>
[/php]



PHP code is simple, I am making an array of cities and area, made 2 functions to get areas and cities and getting the parameters from URL and passing it to functions.

Now the ajax function :

script.js


[js]
function changeArea(cityBox, areaBox) {
jQuery(function($) {

$(areaBox).attr('disabled','disabled');

$(areaBox).addClass('loading');
$.ajax({ //Starting the AJAX
url : 'data.php', //File to be called or pass the data
data : { //Extra paramters
"cityID" : $(cityBox+' option:selected').attr('value')
},
success : function(data) { // The result from data.php file comes as data
window.setTimeout(function(){
$(areaBox).removeAttr('disabled');

$(areaBox).removeClass('loading');

$(areaBox).html('');

$(areaBox).html(data);

}, 2000);
}
});
});
}
[/js]



The above function is is taking two parameters, the select id of City and area. Then I am saving the value of city in a variable, and inside ajax I am passing the value of city to data.php file.

Inside data.php I wrote a function to return areas according to the city ID. Inside success function I am inserting entire result into the area select box.

Simlarly I am going to make another function which will validate the form and if no error then ajax is called and mail is sent.

script.js


[js]
/* Submission of form */

function formSubmit(formID, displayMssgID) {
jQuery(function($) {

var qstring = $(formID).serialize();

var val = $(formID).validate().form();
if (val) {
$(displayMssgID).html('Registering your Request ... Please Wait ...');
$.ajax( {
url : "data.php",
data : qstring,
success : function(data) {

$(displayMssgID).html('');
$(displayMssgID).html(data);
window.setTimeout(function() {

$(displayMssgID).fadeOut();

}, 6000);

}
});
}
});
}
[/js]



This function takes two parameters, ID of the form and result message div. First I am serializing the form, which will take all the form data and store it in a variable. Then I am validating it, if validation is true then our AJAX is called and entire form data is passed to data.php file.

This is return will give some output which I am showing it in id="responseText"

This is a simple way to make AJAX forms, there might be many other tutorials on other websites but I find this very simple. This way you can make any AJAX form. Try out the demo.



Thanks to Jacob for server validation tip.

Jul 18, 2012

JQuery Allow Only Numbers

For a frontend developer when it is asked to do something unique that person will think of JQuery first. Today a simple jquery code to allow only numbers to a text-box. Below code will allow following key events :


  • Backspace

  • Delete

  • Tab

  • Escape

  • Enter

  • Ctrl+A

  • Home

  • end

  • left

  • right



Just add a class to textbox .onlyNumbers and paste the following jquery code :



[js]
$(document).ready(function() {

$(".onlyNumbers").keydown(function(event) {

if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {

if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});

});
[/js]



You can also apply this to textarea.

Demo:





Jul 11, 2012

Simple JQuery Tabs

JQuery tabs. Whenever I start any new project tabs is something which I have to use, so instead of using any external js library I created a small function.

JQuery Tabs



[html]
<div id="tabs">
<div class="divTabs"> <!-- divTabs class is important, this will be passed in function -->
<div id="tab_menu_1" class="tab selected first">PHP</div>
<div id="tab_menu_2" class="tab last">JQUERY</div>
</div>
<div class="divTabs-container">
<div id="divTabs_tab_content_1" class="tabcontent" style="display:block;">Content 1</div>
<div id="divTabs_tab_content_2" class="tabcontent">Content 2</div>
</div>
</div>
[/html]



First we are creating a div with a class name, this class name is really important. This class name will be passed in entire tabs, just check the class naming of the div in the above html. It is prefixed with other classes.

CSS is simple just make the .tabcontent{display:none;}

Now time for js function



[js]
function generateTabs(element) {
jQuery(function($) {
$("."+element+" .tab[id^=tab_menu]").click(function() {
var currentDiv=$(this);
$("."+element+" .tab[id^=tab_menu]").removeClass("selected");
currentDiv.addClass("selected");
var index=currentDiv.attr("id").split("tab_menu_")[1];
$("."+element+"-container .tabcontent").css('display','none');
$("."+element+"-container #"+element+"_tab_content_"+index).fadeIn();
});
});
}
[/js]



Now call this function by passing the classname.
generateTabs('divTabs');

Check the demo below




Jul 3, 2012

HTML5 Air Hockey Game Using Canvas

Air Hockey, my first HTML5 game

In this tutorial you will be learning the importance of canvas tag.


The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph.


Working : A puck(ball) will be freely moving in the table, we just need to stop it from touching the horizontal sides of table by using two mallets.

Let's break our game into pieces, which will help us to code easily. We will be using following javascripts

  • jquery.hotkeys.js - Helps for keyboard events

  • key_status.js - Helps to call required event for our game

  • util.js - Helps to define the mallet position

  • game.js - Our main file which will contain the game functionality



First we will make the canvas in our HTML document.



[html]
<canvas id="canvas" width="480" height="320" tabindex="1"></canvas>
[/html]



Now javascript - game.js


[js]
var canvasElement = document.getElementById("canvas");
var canvas = canvasElement.getContext("2d");

var canvas_width = canvasElement.width;
var canvas_height =canvasElement.height;
var botX = 2;
var botY = 2;
var mx = 2;
var my = 4;
var points = 0;

var init = {};
var FPS = {};

FPS.set = 30;
[/js]



Above, first we created a canvas in our HTML document, and then in game.js we are initializing it, storing its height and width in a variable, declaring some more constant variables.

Let's make our players(mallets) and our ball(puck).



[js]
var player = {
color: "#000",
x: 220,
y: 310,
width: 50,
height: 10,
draw: function() {
canvas.fillStyle = this.color;
canvas.fillRect(this.x, this.y, this.width, this.height);
}
};

var player2 = {
color: "#000",
x: 220,
y: 0,
width: 50,
height: 10,
draw: function() {
canvas.fillStyle = this.color;
canvas.fillRect(this.x, this.y, this.width, this.height);
}
};

var ball = {
x : 2,
y : 2,
r : 5,
draw: function() {
canvas.beginPath();
canvas.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
canvas.fill();
}

};
[/js]



We are defining player1 and player2 and setting its height, width, default position and finally giving it a shape.

HTML5 Air hockey

At this stage if you run the code then you will just find a blank canvas element with no players and no ball. Because we just created the players and ball, we have not set them to do something in canvas. So let's do that now.




[js]

init.interval = setInterval(function(){
update();
draw();
}, 1000/FPS.set);


function update() {
if (keydown.left) {
player.x -= 5;
player2.x -= 5;
}

if (keydown.right) {
player.x += 5;
player2.x += 5;
}

player.x = player.x.clamp(0, canvas_width - player.width);

player2.x = player.x.clamp(0, canvas_width - player.width);

}

function draw() {
canvas.clearRect(0, 0, canvas_width, canvas_height);
player.draw();
player2.draw();
ball.draw();

}
[/js]



Now if you run the file then you'll find that in our canvas a ball and two players will present. If you try to press left and right arrow players will move left/right.

HTML5 Air hockey

In our init() function we call two functions draw() and update() in interval. Update function is used to check any movements or changes in our canvas and it sets the value of players and ball. Draw function will take those values and draw it on canvas.

So if suppose you pressed left arrow once, the update function will take the X position of the player, it will update the new position in the player parameters.

Then the draw function will take the new value from player's parameters and then it will update the canvas, so it appears that the player is actually moving.

And also we are limiting our players to go outside the canvas. We use clamp function to check whether the player has touched the boundaries of the canvas.

Now let's move the ball.



[js]
function draw() {
canvas.clearRect(0, 0, canvas_width, canvas_height);
player.draw();
player2.draw();
ball.draw();

if (ball.x + mx > canvas_width || ball.x + mx < 0){
mx = -mx;
}
if (ball.y + my > canvas_height || ball.y + my < 0){
my = -my;
}

ball.x += mx;
ball.y += my;

}

[/js]



We updated our draw function. Here we use if-else conditions to check the position of the ball. If its touching the boundary then throw it back. mx and my are the variables which helps the ball to give X, Y position. And with its help we change the X, Y co-ordinates of the ball every time.

Now if you run the code, the ball will be moving.

HTML5 Air hockey

But it won't be reacting with the players. Now we will update our draw function one more time to check whether our ball is colliding with player1 or player2.



[js]

function collides(a, b) {
if(a.y == b.y || a.y <= b.height){
if(a.x >= b.x && a.x <= b.x+b.width){
return true;
}else{
return false;
}
}

}

function draw() {
canvas.clearRect(0, 0, canvas_width, canvas_height);
player.draw();
player2.draw();
ball.draw();

if (collides(ball, player)) {

my = -my;

}else if (collides(ball, player2)) {

my = +my;

}else
{
if (ball.x + mx > canvas_width || ball.x + mx < 0){
mx = -mx;
}
if (ball.y + my > canvas_height || ball.y + my < 0){
my = -my;
}


}

ball.x += mx;
ball.y += my;

}


[/js]



As you can see we have created one more function collides(), which takes two parameters. In our draw function we are checking whether ball and player1, ball and player2 are colliding with each other. In our collides() function we are checking position of ball and players. If it returns true, then we change the mx and my value.

Now try running the game again, when the ball hits the players it will return back.

HTML5 Air hockey

Last we will code the game over section. If the ball touched the horizontal boundary of canvas then we end our game.



[js]
function gameOver(){
canvas.fillStyle = '#000';
canvas.font = '18px verdana';
canvas.textBaseline = 'top';
canvas.fillText('Game Over, refresh the page to restart game', 50, 150);

clearInterval(init.interval);

$('#level').removeAttr('disabled');
}

if (ball.y + my > canvas_height || ball.y + my < 0){
my = -my;
gameOver();
}
[/js]



We call gameover() function in our draw function. With help of clearInterval() function we stop the game.


HTML5 Air hockey


So this was the basic game, it can't be completely called Air Hockey but after creating it I found that word to be the best. Still there are many bugs. I just started learning HTML5 and this was my first attempt on a game. You can download this from github, suggestions are always welcomed and fork me if you liked it.

JQuery Slide Left Right | JQuery Toggle Left Right

Recently I completed a project where I had to show a panel to the left side using JQuery, on mouse hover it comes out and on mouse leave it goes back. Its seems to be easy but to maintain the functionality is not that easy.

Here's a small snippet on how to do it.

HTML


[html]
<div id="sidePanel">
<div id="panelContent">
<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2FWebsTutorial&amp;width=200&amp;height=258&amp;colorscheme=light&amp;show_faces=true&amp;border_color&amp;stream=false&amp;header=false&amp;appId=253401284678598" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:258px;" allowTransparency="true"></iframe>
</div>
<div id="panelHandle">
<p>Facebook</p>
</div>

</div>
[/html]




JQuery


[js]
jQuery(function($) {
$(document).ready(function() {
$('#panelHandle').hover(function() {
$('#sidePanel').stop(true, false).animate({
'left': '0px'
}, 900);
}, function() {
jQuery.noConflict();
});

jQuery('#sidePanel').hover(function() {
// Do nothing
}, function() {

jQuery.noConflict();
jQuery('#sidePanel').animate({
left: '-201px'
}, 800);

});
});
});
[/js]



Demo :