Saturday 24 December 2011

Creating a Simple Photo Album with jQuery Similar to Facebook

For the javascript part, I’ve decided to use jQuery as well as the jquery.cycle and jquery.lightbox plugins.


HTML structure


The HTML code needed for a gallery like this is actually rather simple. All we have to do, is to print the images as plain old linked HTML images and wrap image collections in container elements (DIVs).



<h1>My Photo Collection</h1>

<p id="intro">

  This is my photo album...yaddi-yaddi-ya...

</p>

<div class="album">

  <h2>Wicked Album</h2>

  <a href="photos/image1.jpg">

    <img src="photos/thumb_image1.jpg" alt="Lorem" />

  </a>

  <a href="photos/image2.jpg">

    <img src="photos/thumb_image2.jpg" alt="Ipsum" />

  </a>

  <a href="photos/image3.jpg">

    <img src="photos/thumb_image3.jpg" alt="Lorem" />

  </a>

</div>

<div class="album">

  <h2>Wickier Album</h2>

  <a href="photos/image4.jpg">

    <img src="photos/thumb_image4.jpg" alt="Ipsum" />

  </a>

  <a href="photos/image5.jpg">

    <img src="photos/thumb_image5.jpg" alt="Yadi" />

  </a>

  <a href="photos/image6.jpg">

    <img src="photos/thumb_image6.jpg" alt="Yadi" />

  </a>

  <a href="photos/image7.jpg">

    <img src="photos/thumb_image7.jpg" alt="Ya" />

  </a>

</div>

<div class="album">

  <h2>Wickiestest Album</h2>

  <a href="photos/image8.jpg">

    <img src="photos/thumb_image8.jpg" alt="Lorem" />

  </a>

  <a href="photos/image9.jpg">

    <img src="photos/thumb_image9.jpg" alt="Ipsum" />

  </a>

</div>




The Magic of jQuery Plug-Ins


In order to turn this into something a bit more exciting than a bunch of linked images with a blue border, we add some JavaScript and CSS to the page.

First, make sure to include jQuery, jQuery Cycle and jQuery Lightbox to the page. Then add the following JavaScript code to another .js-file that is loaded into the same page:



$(document).ready( function() {

  // Dynamically add nav buttons as these are not needed in non-JS browsers

  var prevNext = '<div id="album-nav"><button ' +

                   'class="prev">&laquo; Previous' +

                   '</button><button>' +

                   'Next &raquo;</button></div>';

  $(prevNext).insertAfter('.album:last');

  // Add a wrapper around all .albums and hook jquery.cycle onto this

  $('.album').wrapAll('<div id="photo-albums"></div>');

  $('#photo-albums').cycle({

    fx:     'turnDown',

    speed:  500,

    timeout: 0,

    next:   '.next',

    prev:   '.prev'

  });

  // Remove the intro on first click -- just for the fun of it

  $('.prev,.next').click(function () {

    $('#intro:visible').slideToggle();

  });

  // Add lightbox to images

  $('.album a').lightBox();

});




You may of course remove the cycling effect.
The only JavaScript you’d then need is $('.album a').lightBox();.

Adding Style Info


Last, we add some style info to make our albums look at least somewhat good.



/** for this example, I don't give a rats (*) about IE */

.album {

  width: 600px !important;

  clear: both;

}

.album h2 {

  clear: both;

}

.album a {

  display: block;

  float: left;

  margin-right: 1em;

  padding: 0.5em;

  border: 1px solid black;

  background-color: #eee;

  text-align: center;

}

.album a:hover {

  border-color: blue;

}

.album img {

  width: 72px;

  height: 100px;

  border: 0;

}

#album-nav {

  margin-top: 1em;

  max-width: 500px;

}

.prev, .next {

  border: 1px outset #ccc;

  color: #000075;

  background-color: white;

  font-weight:bold;

  padding: 0.25em;

}

.prev:hover,.next:hover {

  border-style: inset;

}

.prev {

  float: left;

}

.next {

  float: right;

}




Finish!

Friday 23 December 2011

Lets see how facebook search is so fast

Some days before i came across a very well known website called facebook. And i was always wondering how can such a heavily loaded website be so seamlessly fast.

After a continuous google search, i found that they use AJAX and JQuery extensively with differnet caching technologies along with the following latest technologies.

1. Bigpipe
2. Comet (programming) or "Reverse Ajax"

I have implemented a simple reverse ajax in my website fb.walletchange.com/profile.php @ the search portion. You can mark a remarkable change in search time after implementing the same.

The trick goes like this


a) Load a static page first

b) Pull the data as soon as the page loads using ajax into a hidden div

c) Use jQuery to organise the data for perfect user interactivity

 

    

 

a) Lets create our page layout div first


<DIV id=main>
<H1>Facebook type instant search engine - super speed
</H1>
Filter friends list : <INPUT id=filter>
<DIV id=container>
<DIV>
<UL>
<?php
while($row=mysql_fetch_array($sql_res))
{
$username=$row['username'];

?>
<LI>
<DIV>
<DIV><?=$username?></DIV></DIV></LI>
<?php
}

?>
</UL></DIV></DIV></DIV>


b) We will proceed now by adding jQuery and instant search script and some style attributes to the page


<SCRIPT src="jquery.js"></SCRIPT>

<SCRIPT src="instant-search.js"></SCRIPT>

<STYLE>BODY {
FONT-WEIGHT: 300; FONT-SIZE: 16px; MARGIN: 0px 10%; COLOR: #333; FONT-STYLE: normal; FONT-FAMILY: 'Helvetica Neue', Helvetica, Arial, sans-serif
}
.name SPAN {
BACKGROUND: #fbffc6
}
UL {
PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-TOP: 0px
}
UL LI {
BORDER-RIGHT: #ddd 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #ddd 1px solid; PADDING-LEFT: 5px; FONT-SIZE: 20px; BACKGROUND: #eee; FLOAT: left; PADDING-BOTTOM: 5px; MARGIN: 3px; BORDER-LEFT: #ddd 1px solid; WIDTH: 150px; LINE-HEIGHT: 70px; PADDING-TOP: 5px; BORDER-BOTTOM: #ddd 1px solid; LIST-STYLE-TYPE: none; HEIGHT: 70px; TEXT-ALIGN: center
}
#container {
BORDER-RIGHT: #b9b9b9 1px solid; BORDER-TOP: #b9b9b9 1px solid; MARGIN-TOP: 20px; BORDER-LEFT: #b9b9b9 1px solid; WIDTH: 100%; BORDER-BOTTOM: #b9b9b9 1px solid; HEIGHT: 440px; webkit-box-shadow: 0 0 15px #aaa; moz-box-shadow: 0 0 15px #aaa; box-shadow: 0 0 15px #aaa
}
#container .content {
OVERFLOW: auto; HEIGHT: 440px
}
#main {
MARGIN: 0px auto; WIDTH: 100%;
}
INPUT {
BORDER-RIGHT: #ddd 1px solid; BORDER-TOP: #ddd 1px solid; FONT-SIZE: 20px; BORDER-LEFT: #ddd 1px solid; BORDER-BOTTOM: #ddd 1px solid
}
A {
COLOR: #31499c; TEXT-DECORATION: none
}
H1 {
FONT-WEIGHT: normal; TEXT-ALIGN: center
}
</STYLE>

Facebook loads Web Pages Faster using BigPipe Technology

What is the motivation for this technology?


For an SNS such as Facebook, the major contents must be processed based on personalized data. This means that there is always an inevitable limit to any improvement in performance that is achieved only by improving the speed of the server, such as the cache application and system structure. Facebook found the solution to this limit on performance in a new transfer format, and parallel processing between the server and the client. The solution is particularly focused on reducing the delay in showing the page that is requested.

Problems related to the existing dynamic Web service system


When the Web server is overloaded while generating a page, in most cases the browser becomes idle and does nothing. When the server finishes generating the page and sends it to the browser at once, it cause a bottleneck effect, both in traffic and in performance. Therefore, the server that has already completed transfer cannot be helpful any more. By overlapping the time taken for the server to generate pages and for the browser to render, you can not only reduce the end-to-end latency but also the initial response time for the Web page, consequently reducing overall loading time. The problem in which a single slow query holds back the entire loading process can be addressed as well.

Why BigPipe?


As mentioned earlier, BigPipe is a technology that combines existing Web technologies to allow the parallel processing to generate Web pages and render browsers simultaneously (just as AJAX did). It is named because its mechanism is similar to Pipelining which is common for microprocessors. For this reason, Facebook calls BigPipe technology a Web page pipeline for better performance.

Something you need to know first


In order to understand the BigPipe technology, it is necessary to understand Chunked Encoding, which is supported in version 1.1 of HTTP protocol, and the Script Flush method which is based on Chunked Encoding.

Chunked Encoding


Chunked Encoding is an encoding method of transfer supported in HTTP 1.1 and higher, which allows the server to ignore the header value and divide the response result from HTTP into a series of chunks, and then transfer each chunk of the result. The size of each chunk is transferred along with the content. With this feature, the server can send a response to the Web browser in the middle of a process (Flush transfer) so that the user can see at least partial content.

The figure below shows an example of HTTP responses with a Chunked Encoding format which named Transfer-Encoding from header values as chunked. The sizes of individual chunked text which are transferred sequentially are expressed in hexadecimal instead of the Content-Length header value. You can also see it is ended with 0.

facebook like red notification simple css technique

While developing my current web project, i came across a requirement which has to be lashed with a notification similar style as facebook.

After puting some effort i found out the following implementation.

    

Here is a explanation of the above implementation using CSS and simple javascript.

The css


<style>

.noti_Container {
position:relative;
border:1px solid blue; /* This is just to show you where the container ends */
width:16px;
height:16px;
cursor: pointer;
}
.noti_bubble {
position:absolute;
top: -8px;
right:-6px;
padding-right:2px;
background-color:red;
color:white;
font-weight:bold;
font-size:0.80em;

border-radius:2px;
box-shadow:1px 1px 1px gray;
}

</style>

The HTML code


<div onclick="return f1();">
<img src="friends.png" style="border:none;"/>
<div id="n1">2</div>
</div>

The small javascript code to add some more functionality


<script>
function f1()
{
document.getElementById("n1").style.visibility='hidden';
}
</script>

The final implementation can be found here at http://fb.walletchange.com/profile.php

Sunday 18 December 2011

Cannot send session cache limiter - headers already sent

Use This Php Script at top of the your php page this script start session before dowload include file i hope you will solve this problem.
<?php
if (!isset($_SESSION)) {
session_start();
}
?>

Thursday 15 December 2011

Google plus like drag and drop adding groups


You might have marked a cool feature in google plus, where we add people to groups simply by dragging it to the perticular frame.

Here is a explanation of the above implementation using JQuery and PHP.
Google Plus Style Drag and Drop adding Groups


Sample database contains three tables and relationship between Members and Groups.

Members
Table contains members(users) data such as member_id, member_image and etc.
CREATE TABLE IF NOT EXISTS `members` ( `member_id` int(9) NOT NULL AUTO_INCREMENT, `member_name` varchar(220) NOT NULL, `member_image` text NOT NULL, `dated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`member_id`) );

Groups
Contains groups information.
CREATE TABLE IF NOT EXISTS `groups` ( `group_id` int(9)  AUTO_INCREMENT, `group_name` varchar(220), `sort` int(9), `date` timestamp  DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`group_id`), KEY `sort` (`sort`) );

User_group
Members and Groups table relationship table contains user_id(same as memeber_id), group_id, member_id() and sort(ordering)
CREATE TABLE IF NOT EXISTS `user_group` ( `id` int(9) NOT NULL AUTO_INCREMENT, `user_id` int(9) NOT NULL, `group_id` int(9) NOT NULL, `member_id` int(9) NOT NULL, `sort` int(9) NOT NULL, PRIMARY KEY (`id`) );

Javascript
Here draggable applying for two classes .members and .group
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"></script> <script type="text/javascript" src="jquery.livequery.min.js"></script> <script type="text/javascript" > $(function() { // Initiate draggable for public and groups var $gallery = $( ".members, .group" ); $( "img", $gallery ).live("mouseenter", function() { var $this = $(this); if(!$this.is(':data(draggable)')) { $this.draggable({ helper: "clone", containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", cursor: "move" }); } }); // Initiate Droppable for groups // Adding members into groups // Removing members from groups // Shift members one group to another $(".group").livequery(function(){ var casePublic = false; $(this).droppable({ activeClass: "ui-state-highlight", drop: function( event, ui ) { var m_id = $(ui.draggable).attr('rel'); if(!m_id) { casePublic = true; var m_id = $(ui.draggable).attr("id"); m_id = parseInt(m_id.substring(3)); } var g_id = $(this).attr('id'); dropPublic(m_id, g_id, casePublic); $("#mem"+m_id).hide(); $( "<li></li>" ).html( ui.draggable ).appendTo( this ); }, out: function(event, ui) { var m_id = $(ui.draggable).attr('rel'); var g_id = $(this).attr('id'); $(ui.draggable).hide("explode", 1000); removeMember(g_id,m_id); } }); }); // Add or shift members from groups function dropPublic(m_id, g_id,caseFrom) { $.ajax({ type:"GET", url:"groups.php?m_id="+m_id+"&g_id="+g_id, cache:false, success:function(response){ $.get("groups.php?reload_groups", function(data){ $("#groupsall").html(data); $("#added"+g_id).animate({"opacity" : "10" },10); $("#added"+g_id).show(); $("#added"+g_id).animate({"margin-top": "-50px"}, 450); $("#added"+g_id).animate({"margin-top": "0px","opacity" : "0" }, 450); }); } }); } // Remove memebers from groups // It will restore into public groups or non grouped members function removeMember(g_id,m_id) { $.ajax({ type:"GET", url:"groups.php?do=drop&mid="+m_id, cache:false, success:function(response){ $("#removed"+g_id).animate({"opacity" : "10" },10); $("#removed"+g_id).show(); $("#removed"+g_id).animate({"margin-top": "-50px"}, 450); $("#removed"+g_id).animate({"margin-top": "0px","opacity" : "0" }, 450); $.get("groups.php?reload", function(data){ $("#public").html(data); }); } }); } }); </script>

groups.php
<?php require_once("multipleDiv.inc.php"); // Initiate Object $obj = new Multiplediv(); // Add or Update Ajax Call if(isset($_GET['m_id']) and isset($_GET['g_id'])) { $obj->addMembers((int)$_GET['m_id'], (int)$_GET['g_id']); exit; } // Remove Memebers from groups Ajax call if(isset($_GET['do'])) { $obj->removeMember($_GET['mid']); exit; } // Reload groups each ajax call if(isset($_GET['reload'])){ echo $obj->getMembers_reload(); exit; } if(isset($_GET['reload_groups'])){ echo $obj->getmembergroups_reload(); exit; } // Initiate Groups and members $members = $obj->public_members(); $groups = $obj->groups(); ?> Friends <div id="main_portion"> <div id="public"> <!-- Initiate members --> <?php if(!isset($members)) $members = $obj->public_members(); if($members) { foreach($members as $member) { extract($member); echo "<div class='members' id='mem".$member_id."'>\n"; echo "<img src='images/".$member_image."' rel='".$member_id."'>\n"; echo "<b>".ucwords($member_name)."</b>\n"; echo "</div>"; } } else echo "Members not available"; ?> </div> <div id="groupsall"> Groups <!-- Initiate Groups --> <?php if(!isset($groups)) $groups = $obj->groups(); if($groups) { foreach($groups as $group) { extract($group); echo "<div id='".$group_id."' class='group'>\n"; echo ucwords($group_name); echo "<div id='added".$group_id."' class='add' style='display:none;' ><img src='images/green.jpg'></div>"; echo "<div id='removed".$group_id."' class='remove' style='display:none;' ><img src='images/red.jpg'></div>"; echo "<ul>\n"; echo $obj->updateGroups($group_id); echo "</ul></div>"; } } ?>


multipleDiv.inc.php
Download this and modify database connection credentials.
<?php // Database declaration's define("SERVER", "localhost"); define("USER", "username"); define("PASSWORD", "password"); define("DB", "database");class Multiplediv { ........................ ........................ ......................... } ?>

XAMPP Access to the requested directory is only available from the local network.

I searched a lot about this issue and found the simplest solution:

Mark the like "Deny from all" as a comment at the <LocationMatch attribute present at the end of the file (C:\XAMPP\apache\conf\extra\httpd-xampp.conf)

Subsequently i added into my verified list of solutions at http://itswadesh.wordpress.com

Saturday 3 December 2011

Pagination with Jquery, PHP , Ajax and MySQL.

Friends, In my current employment i need to develop huge database driven web application. Which normally deals with millions  of records. I use indexing and cache techniques. Along with that i use jquery to make it handy for end use.

   

Database
MySQL messages table contains two columns msg_id and message
CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message VARCHAR(150)
);

JavaScript Code
This script works like a data controller.
<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()
{function loading_show()
{
$('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}function loading_hide()
{
$('#loading').fadeOut();
}

function loadData(page)
{
loading_show();
$.ajax
({
type: "POST",
url: "load_data.php",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
});

</script>


load_data.php
Contains PHP coding. Displaying data from the messages table.
<?php
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15; // Per page records
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include"db.php";
$query_pag_data = "SELECT msg_id,
message from messages LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data)
or die('MySql Error' . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result_pag_data))
{
$htmlmsg=htmlentities($row['message']); //HTML entries filter
$msg .= "<li><b>" . $row['msg_id'] . "</b> " . $htmlmsg . "</li>";
}
$msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
/* -----Total count--- */
$query_pag_num = "SELECT COUNT(*) AS count FROM messages"; // Total records
$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);
/* -----Calculating the starting and endign values for the loop----- *///Some Code. Available in download script }
?>


Enhanced by Zemanta

Upload and Resize an Image with PHP

I had implemented a simple PHP script to re-sizing image into different dimensions. It's very useful to your web projects to save hosting space and bandwidth to reduce the original image to compressed size.




 

PHP Code
This script resize an Image into two 60px and 25px. Take a look at $newwidth you have to modify size values.

<?php 

define ("MAX_SIZE","400");

$errors=0;

if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];

if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") 
&& ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";
$errors=1;
}

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);

$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
//If no errors registred, print the success message

if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update SQL statement ");
echo "Image Uploaded Successfully!";

}
?>



Extention PHP funtion
Finds file extensions.

function getExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; } 
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}


Enhanced by Zemanta

configuring php to connect with oracle database using XAMPP server manager



[caption id="" align="alignright" width="190" caption="Image via CrunchBase"]Image representing Windows as depicted in Crun...S[/caption]

Today i was searching for "how to configure php to connect with oracle ".  I tried different search words and searched the whole internet. Finally i was successful.

I use the package XAMM for windows to run PHP and MySql.

Step-A


Check whether you have oracle client already installed

  1. In your XAMPP Start Page, go to phpinfo, look for string oci8. If string found it indicate that connection to oracle is available and simply execute Step-3.           Otherwise to activate connection do the following steps:

  2. Open the currently used php.ini file by looking at the phpinfo, from the XAMPP folder.

  3. Find string ;extension=php_oci8.dll. Remove the semicolon (;) from the begining of the string to activate the oracle extension.

  4. Save the php.ini file.

  5. Download the “Instant Client Package – Basic” for Windows from the OTN Instant Client page. Unzip it to "C:\xampp\php\ext" folder

  6. Edit the PATH environment setting and add C:\xampp\php\ext before any other Oracle directories. For example, on Windows XP, follow Start -> Control Panel -> System -> Advanced -> Environment Variables and edit PATH in the System variables list.

  7. Set desired Oracle globalization language environment variables such as NLS_LANG. If nothing is set, a default local environment will be assumed. See An Overview on Globalizing Oracle PHP Applications for more details.

  8. Unset Oracle variables such as ORACLE_HOME and ORACLE_SID, which are unnecessary with Instant Client (if they are set previously).

  9. Restart XAMPP (or Start if its not already started).

  10. To make sure that connection to oracle database has successfully activated, go to phpinfo. Find string: oci8. If found, then XAMPP can now communicate with Oracle Database.


Step-B


Now connect to your desired database and execute your query

<?php

define('DB_SERVER', 'yourservername');
define('DB_USERNAME', 'yourUserName');
define('DB_PASSWORD', 'yourPassword');
define('DB_DATABASE', 'yourDatabaseName');
$conn= oci_connect(DB_USERNAME, DB_PASSWORD, DB_SERVER)
or die(oci_error());
echo "success...";
//$database = oci_select_db(DB_DATABASE) or die(oci_error());
$stid = oci_parse($conn, 'SELECT * FROM employees'); oci_execute($stid); echo "<table border='1'>\n"; while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {     echo "<tr>\n";     foreach ($row as $item) {         echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";     }     echo "</tr>\n"; } echo "</table>\n";
?>

For further help you can always refer the PHP manual.
Enhanced by Zemanta

Friday 2 December 2011

Ways to check BSNL Broadband or Dataone internet usage

[caption id="" align="alignright" width="300" caption="Image via Wikipedia"]BSNL logo[/caption]

BSNL broadband is still the most popular and widely used broadband service in India. BSNL brought the low cost and high speed broadband service in India (Though we are still far slower than other developed countries). Many people use BSNL‘s fixed traffic plans, we need to keep eyes on our usages in these plans. (Though I am on unlimited plan, I use (love) to track how many GBs I have downloaded till now.)

There are many ways to check the usages. Here I am giving a list of good software, sites, and services to check how much internet you have used.

Official links.


The official links are the most reliable sources to check the usages.
For 5x.xx.xx.xx IP-Address.

  • http://10.240.64.195

  • http://10.240.89.199

  • http://10.240.128.195

  • http://10.240.16.195

  • http://10.240.144.195


For 117.xx.xx.xx IP-Address

  • http://data.bsnl.in/wps/portal


Softwares


There are few unofficial softwares available on net to check the internet usage. ShaPlus Usage Finder is one of the most popular amongst them, You can download it from shaplus.com/dataone/

Awesome tools and services


Now this is the best and important part of this post.

1. SMS Alert:
This is the official service, which sends SMS and E-Mail alerts for usages.
You can register yourself for the service at http://bbusage.bsnl.in/

2. DataFox – Firefox and Chrome Browser Plug-in.
DataFox is nice Mozilla Firefox and Google Chrome plug-in which shows the BrandBand usages in browser itself. Its very nice and handy utility. No need to check any special software or no need to visit any URL for checking the usages. Just give the login credentials to plug-in and the plug-in will automatically fetch and display the usages in browser status bar.
You can download and install DataFox from TheGoan.com/DataFox/


Do you know any other good service / Software ?
Am I missing anything here ??
Let me know. Comment below.

Enhanced by Zemanta

Thursday 1 December 2011

Login with Facebook and Twitter

Facebook and Twitter have become large in the social network world and both networks offering oAuth support. We developed a system to login with Twitter and Facebook. Nowadays web users not interested to filling the big registration forms. This script helps you to avoid registration forms, It’s is very useful and simple to integrate.



   



Database



Sample database users table columns id, email, oauth_uid, oauth_provider
and username.


CREATE TABLE users
(
id INT PRIMARY
KEY
AUTO_INCREMENT,
email VARCHAR(70),

oauth_uid VARCHAR(200),
oauth_provider VARCHAR(200),
username VARCHAR(100),

twitter_oauth_token VARCHAR(200),

twitter_oauth_token_secret VARCHAR(200)

);



The tutorial contains three folders called facebook,twitter and
config
with PHP files.

facebook //Facebook
OAUTH library


twitter //Twitter
OAUTH library


config
-- functions.php 
-- dbconfig.php
//Database connection


-- fbconfig.php
//Facebook API connection

-- twconfig.php
//Twitter API connection

index.php
home.php
login-twitter.php
login-facebook.php
getTwitterData.php




Facebook Setup



You have to create a application. Facebook will provide you app
id
and app secret id, just modify following code



fcconfig.php

<?php
define('APP_ID', 'Facebook
APP ID
');
define('APP_SECRET', 'Facebook
Secret ID
');
?>






Twitter Setup



Create a twitter application click here. Some like Facebook Twitter provide you
consumer key amd consumer secret key using these modify following code.

twconfig.php



<?php
define('YOUR_CONSUMER_KEY', 'Twitter Key');
define('YOUR_CONSUMER_SECRET', 'Twitter Secret Key');
?>




dbconfig.php
Database configuration file.




<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'User
Name
');
define('DB_PASSWORD', 'Password');
define('DB_DATABASE', 'DATABASE');
$connection = mysql_connect(DB_SERVER,
DB_USERNAME, DB_PASSWORD) or
die
(mysql_error());
$database = mysql_select_db(DB_DATABASE)
or die(mysql_error());
?>




login-twitter.php
In root directory find out the below line at i>login-twitter.php code and
replace yourwebsite.





$request_token =
$twitteroauth->getRequestToken('http://yourwebsite.com/getTwitterData.php');





index.php


If you want to modify your web project existing login or index pages, just use
following code.


<?php
session_start();
if (isset($_SESSION['id'])) {
// Redirection to login
page twitter or facebook

header("location: home.php");
}
if (array_key_exists("login", $_GET))

{
$oauth_provider = $_GET['oauth_provider'];
if ($oauth_provider == 'twitter')
{
header("Location: login-twitter.php");
}
else if ($oauth_provider == 'facebook')
 {
header("Location:
login-facebook.php
");
}
}
?>
//HTML Code
<a href="?login&oauth_provider=twitter">Twitter_Login</a>
<a href="?login&oauth_provider=facebook">Facebook_Login</a>


Tuesday 29 November 2011

Facebook Style Alert Confirm Box with jQuery and CSS

                 

Create a facebook style alert box with jquery plug-in jquery.alert.js. Bellow is the complete tutorial

HTML / Javascript Code
Contains javascript and HTML Code.



<link href="facebook.alert.css" rel="stylesheet" type="text/css">

<script type="text/javascript"

src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript" src="jquery.alert.js"></script>

<script type="text/javascript"> $(document).ready( function()

{ $("#delete_confirm").click( function()

{ jConfirm('Are you sure you want ot delete this thread?', '', function(r)

{ if(r==true) { $("#box").fadeOut(300); } }); }); });

</script>
<div id="box" style=" background-color:#ffffcc;">

<a href="#" id="delete_confirm">Delete</a>

</div>



facebook.alert.css
Contains CSS code.



#popup_container

{

font-family:'Lucida Grande',arial;

font-weight:bold;

text-align:left;

font-size: 12px;

width: 364px;

height: 86px;

background: #F3F3F3;

border:solid 1px #dedede;

border-bottom: solid 2px #456FA5;

color: #000000; }
#popup_title

{ display:none; }
#popup_message

{ padding-top: 15px; padding-left: 15px; }
#popup_panel

{ text-align: left; padding-left:15px; }
input

{

background-color:#476EA7;

padding:3px; color:#FFFFFF;

margin-top:20px;

margin-right:10px;

}


Hack an Website ? SQL Injection ? Very simple

Are you looking for some useful tips to improve your web projects security? In this post I suggest you some interesting points about this topic.

Hacking is very interesting topic you can improve programming skill.

SQL Injection

SQL Injection like this

Login Java Code
String userid = request.getParameter("userid");
String password = request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:projectDB");query = "SELECT * FROM Users WHERE user_id ='" + userid + "' AND password ='" + password +"'";

PreparedStatement ps = connection.prepareStatement(query);
ResultSet users = ps.executeQuery();

if(users.next()){

//some thing here
}
else{

}


Injection Works like this
query = "SELECT * FROM Users WHERE user_id ='' OR 1=1; /* AND password ='*/--'";

Login PHP Code;
Username = ' OR 1=1;//
Password = ....
$myusername=$_POST['usr'];
$mypassword=$_POST['pwd'];$sql="SELECT * FROM users WHERE user='$myusername' and password='$mypassword'";

$result=mysql_query($sql);
$count=mysql_num_rows($result);

if($count==1){

//some code
}
else {

}


Injection Works like this
$sql="SELECT * FROM users WHERE user=''OR 1 = 1;//' and password='....'";

How to avoid these mistakes Use addSlashes() function adding slashes(/) to the string in java and php
//Java Code
addSlashes(String userid);// PHP Code
$myusername=addslashes($_POST['usr'];);


Hacker is intelligent than programmer. So always hide the file extension (eg: *.jsp,*.php,*.asp).

http://xyz.com/login.php to http://xyz.com/login
http://xyz.com/login to http://xyz.com/signin.do
In Java redirect this URL links using Web.xml file and inn php write .htaccess file in root directory.

My Best Hacking Training Site Hackthissite.org

Hacker's Game full control with Unix based commands. Play and learn many more hacking things

http://itswadesh.wordpress.com/2011/11/29/prepared-statements-in-php-and-mysqli/

Prepared Statements in PHP and MySQLi

This article is intended for readers who have experience using PHP and MySQL. You should also have a general understanding of databases and programming (both procedural and object-oriented) as well as how to use PHP to execute a simple query to MySQL. I will not cover how to install PHP or MySQL, however at the end of the article are some links to help you get started with the installation process and for some further reading on the subject. I will be covering the basics of prepared statements in PHP and MySQLi and why you should consider using them in your own code as well as some technical explanation as to why you should use them.

Introduction

If you are like me and most other people, you probably have not taken the time to learn about web security when you first started writing server-side code. This is very dangerous as most people never even go back and try to make their code secure (or they simply forget). Writing their code in the same way that they originally learned how to can cause some serious vulnerabilities in the code, allowing hacking techniques such as SQL Injections to be fairly easy. If you have no idea what MySQL injections or cross side scripting is, then you should do some research, for example just go to Google and type in "SQL Injections" and there will be plenty of reading for you. I also would recommend a book called, "How to Break Web Software", it is a fantastic book that one of my professors told one of my classes about. It can teach you a lot about security, it is highly recommended. I will have an article written shortly on SQL Injections, so check back soon! If you do know what some of these nasty hacking techniques are then you are probably wondering why you should want to use prepared statements. There are basically three reasons why you should seriously consider writing prepared statements to execute your queries.

1. Prepared statements are more secure.
2. Prepared statements have better performance.
3. Prepared statements are more convenient to write.

Now that we know why prepared statements are better, let’s build an example so you can see for yourself. We’ll build a simple login example using prepared statements. First, I’ll show you the way most people would write it, then I’ll show you the way you could do it with a prepared statement which will be more secure, have better performance and be more convenient to write. Let’s get started!

The Well-known Way

If you are reading this article, chances are you already know how to execute a simple MySQL query in PHP. For those of you who do not know how to do this, it would look similar to this:

/* Connect to the Database */

$dbLink = mysql_connect("localhost", "username", "password");

if (!dbLink) {
echo 'db link fail';
}

/* Select the database */
mysql_select_db("databaseName");

/* Query and get the results */
$query = "SELECT * FROM testUsers WHERE username='$user' AND
password='$pass'";
$result = mysql_query($query);

/* Loop through the results */
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "Username: " . $row["username";
}


What is the problem with this code? Simple, someone could use a simple SQL injection to get around the password authentication. Why is this code angerous? If you know what an SQL injection does, it basically bypasses the password condition by commenting it out and uses an always true statement which allows access. Building strings on the fly like this should make you very nervous, but how do we make it more secure? Say hello to prepared statements.

Prepared Statements

What is so great about prepared statements and why are they more secure? The simple answer is because prepared statements can help increase security by separating the SQL logic from the data being supplied. In the previous example we saw how the data is basically built into the SQL logic by building the query as a string on the fly. Let’s take a look at what a prepared statement can look like.

/* Create a new mysqli object with database connection parameters */

$mysqli = new mysql('localhost', 'username', 'password', 'db');

if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */

if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters

s - string, b - boolean, i - int, etc */

$stmt -> bind_param("ss", $user, $pass);

/* Execute it */
$stmt -> execute();
/* Bind results */

$stmt -> bind_results($result);
/* Fetch the value */

$stmt -> fetch();

echo $user . "'s level of priviledges is " . $result;
/* Close statement */

$stmt -> close();
}
/* Close connection */

$mysqli -> close();


Doesn’t look too bad, right? In short, the above code basically creates a new mysqli object and connects to the database. We then create a prepared statement and bind the incoming parameters to that statement, execute it and get the result. We then close the statement and connect and we’re done! Pretty easy!

Let’s take a look at where the security happens in these few lines:
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
$stmt -> bind_param("ss", $user, $pass);

Instead of grabbing and building the query string using things like $_GET['username'], we have ?'s instead. These ?'s separate the SQL logic from the data. The ?'s are place holders until the next line where we bind our parameters to be the username and password. The rest of the code is pretty much just calling methods which you can read about by following some of the links at the end of the article.

I hope this was helpful to you and if you have any questions feel free to post some comments below!

Saturday 26 November 2011

Old Standalone Softwares link

These days most of  the products are moving into its lite version. Sometimes i need a standalone copy of it to be saved into my computer so that every time i install windows XP i need not have to download those again.

So i collected links of essential softwares. And here are those.

Adobe Acrobat Reader Version 8

Google Chrome Standalone

Skype Standalone Offline Installer

Download AVG Antivirus 2012 32-bit (137 MB)

You are always welcome to add more links helping your friends find all of them at one place.

Facebook Style Footer Admin Panel

                 

The popularity of social media has been booming in the past few years and Facebook definitely has climbed high to the top of the social network rankings. Facebook has many Ajax driven features and applications that are very impressive, and one of the things I particularly like is the footer admin panel, where it neatly organizes frequently used links and applications.

This week I would like to cover part 1 of how to recreate the Facebook footer admin panel with CSS and jQuery.


Step 1. Wireframe and Tooltip Bubbles – HTML & CSS


Lay out the wireframe of the admin panel using an unordered list for the foundation. The last two list items (Alert Panel & Chat Panel) will have sub-panels nested within them. Since these two panels will float to the right, the order in the markup will be reversed.

Tooltip foundation

Notice that there is a <small> tag nested within the <a> tag, this is how we will achieve our tooltip bubble on the navigation.

HTML


<div id="footpanel">
<ul id="mainpanel">
<li><a href="#">Inspiration <small>
Design Bombs</small></a></li>
<li><a href="#">View Profile <small>
View Profile</small></a></li>
<li><a href="#">Edit Profile <small>
Edit Profile</small></a></li>
<li><a href="#">Contacts <small>
Contacts</small></a></li>
<li><a href="#">Messages (10) <small>
Messages</small></a></li>
<li><a href="#">Play List <small>
Play List</small></a></li>
<li><a href="#">Videos <small>
Videos</small></a></li>
<li id="alertpanel"><a href="#">
Alerts</a></li>
<li id="chatpanel"><a href="#">
Friends (<strong>18</strong>)</a></li>
</ul>
</div>

CSS


First start by fixing the panel to the bottom of the viewport.
#footpanel {
position: fixed;
bottom: 0; left: 0;
z-index: 9999;
/*--Keeps the panel on top of all other elements--*/
background: #e3e2e2;
border: 1px solid #c3c3c3;
border-bottom: none;
width: 94%;
margin: 0 3%;
}

As you may already know, IE6 does not understand fixed positioning. I stumbled across a tutorial that fixed this problem*.
*html #footpanel { /*--IE6 Hack - Fixed Positioning to the Bottom--*/
margin-top: -1px;
/*--Prevents IE6 from having an infinity scroll bar - due to 1px border on #footpanel--*/
position: absolute;
top:expression(eval(
document.compatMode &&document.compatMode=='CSS1Compat')
?documentElement.scrollTop+(
documentElement.clientHeight-this.clientHeight)
: document.body.scrollTop +(
document.body.clientHeight-this.clientHeight));
}

*Note: Due to heavy loading on the browser, an alternative solution would be to either use an position: absolute; or if the situation/client allows it use display: none; for those with IE6.

Style the unordered list which will be the foundation of this panel.
#footpanel ul {
padding: 0; margin: 0;
float: left;
width: 100%;
list-style: none;
border-top: 1px solid #fff;
/*--Gives the bevel feel on the panel--*/
font-size: 1.1em;
}
#footpanel ul li{
padding: 0; margin: 0;
float: left;
position: relative;
}
#footpanel ul li a{
padding: 5px;
float: left;
text-indent: -9999px;
/*--For text replacement - Shove text off of the page--*/
height: 16px; width: 16px;
text-decoration: none;
color: #333;
position: relative;
}
html #footpanel ul li a:hover{ background-color: #fff; }
html #footpanel ul li a.active {
/*--Active state when sub-panel is open--*/
background-color: #fff;
height: 17px;
margin-top: -2px;
/*--Push it up 2px to attach the active button to sub-panel--*/
border: 1px solid #555;
border-top: none;
z-index: 200;
/*--Keeps the active link on top of the sub-panel--*/
position: relative;
}

Tooltip Demo

Declare the text replacement for each link.
You can download these great icons by Pinvoke here.
#footpanel a.home{
background: url(home.png) no-repeat 15px center;
width: 50px;
padding-left: 40px;
border-right: 1px solid #bbb;
text-indent: 0;
/*--Reset text indent since there will be a
combination of both text and image--*/
}
a.profile{ background: url(user.png)
no-repeat center center; }
a.editprofile{ background: url(wrench_screwdriver.png)
no-repeat center center; }
a.contacts{ background: url(address_book.png)
no-repeat center center; }
a.messages{ background: url(mail.png)
no-repeat center center; }
a.playlist{ background: url(document_music_playlist.png)
no-repeat center center; }
a.videos{ background: url(film.png)
no-repeat center center; }
a.alerts{ background: url(newspaper.png)
no-repeat center center; }
#footpanel a.chat{
background: url(balloon.png)
no-repeat 15px center;
width: 126px;
border-left: 1px solid #bbb;
border-right: 1px solid #bbb;
padding-left: 40px;
text-indent: 0;
/*--Reset text indent since there will be
a combination of both text and image--*/
}
#footpanel li#chatpanel, #footpanel li#alertpanel {
 float: right; }
/*--Right align the chat and alert panels--*/

Tooltip Demo

Style the tooltip bubble, by default the <small> tag will be hidden with a display:none;. On hover over, allow the tooltip to appear with a display:block;
#footpanel a small {
text-align: center;
width: 70px;
background: url(pop_arrow.gif) no-repeat center bottom;
padding: 5px 5px 11px;
display: none; /*--Hide by default--*/
color: #fff;
font-size: 1em;
text-indent: 0;
}
#footpanel a:hover small{
display: block; /*--Show on hover--*/
position: absolute;
top: -35px;
/*--Position tooltip 35px above the list item--*/
left: 50%;
margin-left: -40px; /*--Center the tooltip--*/
z-index: 9999;
}

Friday 25 November 2011

What is jQuery?

Since you've come to this page, you may already have a pretty good idea about what jQuery is, but to be on the safe side, here is a brief explanation. jQuery is a JavaScript framework, which purpose is to make it much easier to use JavaScript on your website. You could also describe jQuery as an abstraction layer, since it takes a lot of the functionality that you would have to write many lines of JavaScript to accomplish and wraps it into functions that you can call with a single line of code. It's important to note that jQuery does not replace JavaScript, and while it does offer some syntactical shortcuts, the code you write when you use jQuery is still JavaScript code. With that in mind, you should be aware that you don't need to be a JavaScript expert to use jQuery. In fact, jQuery tries to simplify a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation, so that you may do these things without knowing a lot about JavaScript. There are a bunch of other JavaScript frameworks out there, but as of right now, jQuery seems to be the most popular and also the most extendable, proved by the fact that you can find jQuery plugins for almost any task out there. The power, the wide range of plugins and the beautiful syntax is what makes jQuery such a great framework. Keep reading to know much more about it and to see why we recommend it.

Getting started

To use jQuery, you need to include it on the pages where you wish to take advantage of it. You can do this by downloading jQuery from their website at www.jquery.com. There is usually a choice between a "Production" version and a "Development" version. The first is for your live website, because it has been minified and compressed to take up the least amount of space, which is important for your visitors, whose browser will have to download the jQuery file along with the rest of your website. For testing and development, the "Development" version is best. It hasn't been minified or compressed, so when you run into an error, you can actually see where in jQuery it happens.

Once downloaded, you will have to reference the jQuery JavaScript file on your pages, using the <script> HTML tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you wish to use it and then reference it like this, in the section of your document:

<script type="text/javascript" src="jquery-1.5.1.js"></script>

A part of your page should now look something like this:

<head>
        <title>jQuery test</title>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
</head>

A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most CDN's will make sure that once a user requests a file from it, it's served from the server closest to them, so your European users won't have to get the file all the way from the US and so on.

You can use jQuery from a CDN just like you would do with the downloaded version, only the URL changes. For instance, to include jQuery 1.5.1 from Google, you would write the following:

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself. Here is a link to the jQuery CDN information from Google:

http://code.google.com/intl/da/apis/libraries/devguide.html#jquery

Or if you prefer to use it from Microsoft:

http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0

Read on to learn how to start using jQuery.

Hello, world!

Every decent programming tutorial will start with a "Hello, world!" example and this tutorial is yet another one of them. In the previous chapter, we learned how to include jQuery on our page, so that we may start using all of its great features. You need to know a bit more about how jQuery works, before you can start writing your own code, but just to make sure that everything is working, and for you to see how simple jQuery is, let's kick off with a little example:

<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>

Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.

Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:

<div id="divTest2"></div>
<script type="text/javascript">
document.getElementById("divTest2").innerHTML = "Hello, world!";
</script>

And it would be even longer if our HTML element didn't have an ID, but for instance just a class.

Normally though, you wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready. Fortunately, jQuery makes this very easy as well, as we will see in the next chapter. After that, we will start looking into one of the most important aspects of jQuery, which has already been used in the above example: Selectors.

The ready event

As mentioned in the previous chapter, it's good practice to wait for the document to be fully loaded and ready, before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section, either directly or through a link to an external JavaScript file. You may do just that by placing your code inside the document ready event. We will use the same example as in the "Hello, world!" chapter, but this time the code is inside the ready event:

<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#divTest1").text("Hello, world!");  
}

$(document).ready(DocumentReady);
</script>

What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.

However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:

<div id="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#divTest2").text("Hello, world!");  
});
</script>

But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:

<div id="divTest3"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest3").text("Hello, world!");  
});
</script>

In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.

As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.

Method chaining

Yet another one of the really cool aspects of jQuery is the fact that most of the methods returns a jQuery object that you can then use to call another method. This allows you to do command chaining, where you can perform multiple methods on the same set of elements, which is really neat because it saves you and the browser from having to find the same elements more than once. Here's an example, and don't worry about the jQuery methods used in the following examples - they will be explained in later chapters:

<div id="divTest1"></div>
<script type="text/javascript">
        $("#divTest1").text("Hello, world!").css("color", "blue");
</script>

It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.

We can add more method calls if needed, but at some point, the line of code will become quite long. Fortunately for us, JavaScript is not very strict when it comes to the syntax, so you can actually format it like you want, including linebreaks and indentations. For instance, this will work just fine as well:

<div id="divTest2"></div>
<script type="text/javascript">
        $("#divTest2").text("Hello, world!")
                                        .removeClass("blue")
                                        .addClass("bold")
                                        .css("color", "blue");                                  
</script>

JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.

Note that some methods doesn't return the jQuery object, while others only return it depending on the parameters you pass to it. A good example of that is the text() method used above. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object.

Introduction to jQuery selectors

A very common task when using JavaScript is to read and modify the content of the page. To do this, you need to find the element(s) that you wish to change, and this is where selector support in jQuery will help you out. With normal JavaScript, finding elements can be extremely cumbersome, unless you need to find a single element which has a value specified in the ID attribute. jQuery can help you find elements based on their ID, classes, types, attributes, values of attributes and much, much more. It's based on CSS selectors and as you will see after going through this tutorial, it is extremely powerful.

Because this is such a common task, the jQuery constructor comes in several forms that takes a selector query as an argument, allowing you to locate element(s) with a very limited amount of code for optimal efficiency. You can instantiate the jQuery object simply by writing jQuery() or even shorter using the jQuery shortcut name: $(). Therefore, selecting a set of elements is as simple as this:

$(<query here>)

With the jQuery object returned, you can then start using and altering the element(s) you have matched. In the following chapters, you will see examples of some of the many ways you can select elements with jQuery.

Using elements, ID's and classes

The #id selector


A very common selector type is the ID based, which we saw in the "Hello, world" example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:
$("#divTest")

An example of it in use:

<div id="divTest"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest").text("Test");
});
</script>

Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.

The .class selector


Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:

<ul>
        <li class="bold">Test 1</li>
        <li>Test 2</li>
        <li class="bold">Test 3</li>
</ul>
<script type="text/javascript">
$(function()
{
        $(".bold").css("font-weight", "bold");
});
</script>

The element selector


You can also match elements based on their tag names. For instance, you can match all links on a page like this:

$("a")

Or all div tags like this:

$("div")

If you use a multi-element selector, like the class selector we used in the previous example, and we know that we're looking for elements of a specific type, it's good practice to specify the element type before the selector. Not only is it more precise, it's also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:
$("span.bold").css("font-weight", "bold");

This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well.

Selectors can do much more for you though. Read on for more cool examples.

Using attributes

In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them.

Find elements with a specific attribute


The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:

<span title="Title 1">Test 1</span><br />
<span>Test 2</span><br />
<span title="Title 3">Test 3</span><br />

<script type="text/javascript">
$(function()
{
        $("[title]").css("text-decoration", "underline");
});
</script>

We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.

Find elements with a specific value for a specific attribute


Here's an example where we find elements with a specific value:

<a href="http://www.google.com" target="_blank">Link 1</a><br />
<a href="http://www.google.com" target="_self">Link 2</a><br />
<a href="http://www.google.com" target="_blank">Link 3</a><br />

<script type="text/javascript">
$(function()
{
        $("a[target='_blank']").append(" [new window]");
});
</script>

The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");

The difference is the != instead of =, a common way of negating an operator within many programming languages.

And there's even more possibilities:

Find elements with a value which starts with a specific string using the ^= operator:
$("input[name^='txt']").css("color", "blue");

Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");

Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");

Parent/child relation selectors

jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element.

The syntax for finding children which are direct descendants of an element looks like this:

$("div > a")

This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:

$("div a")

Here's an example where we color bold tags blue if they are directly descending from the first test area:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");
</script>

As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");
</script>

Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.

Fading elements

Doing simple animation is very easy with jQuery. One of the effects it supports out-of-the-box, is fading an element in and out of visibility. Here's a simple example, where we fade in an otherwise hidden box, using the fadeIn() method:



<div id="divTestArea1" style="padding: 50px;
background-color: #89BC38; text-align: center; display: none;">
        <b>Hello, world!</b>
</div>
<a href="javascript:void(0);" onclick="ShowBox();">Show box</a>
<script type="text/javascript">
function ShowBox()
{
        $("#divTestArea1").fadeIn();
}
</script>

You can fade a lot of different elements, like divs, spans or links. The fadeIn() method can take up to three parameters. The first one allows you to specify the duration of the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds. Here's an example of it in use:



<div id="divTestArea21" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div>
<div id="divTestArea22" style="width: 50px; height: 50px; display: none;
background-color: #C3D1DF;"></div>
<div id="divTestArea23" style="width: 50px; height: 50px; display: none;
background-color: #9966FF;"></div>
<a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a>
<script type="text/javascript">
function ShowBoxes()
{
        $("#divTestArea21").fadeIn("fast");
        $("#divTestArea22").fadeIn("slow");
        $("#divTestArea23").fadeIn(2000);
}
</script>

Don't mind all the HTML, it's just there so that you can see the difference between the fading durations. Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the fadeOut() method, which obviously has the reverse effect of fadeIn():



<div id="divTestArea3" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea3").fadeIn(2000, function()
        {
                $("#divTestArea3").fadeOut(3000);
        });
});
</script>

There may be situations where you want to fade an element in our out depending on its current state. You could of course check if it is visible or not and then call either fadeIn() or fadeOut(), but the nice jQuery developers have supplied us with a specific method for toggling an element, called fadeToggle(). It takes the same parameters as fadeIn() and fadeOut(), so it's very easy to use. Here's a little example:



<div id="divTestArea4" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div><br />
<a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a>
<script type="text/javascript">
function ToggleBox()
{
        $("#divTestArea4").fadeToggle("slow");  
}
</script>

And that's how easy it is to use the fading effects of jQuery.