Print selected webpage data using Javascript

Many times we would like to place a button on webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object.

The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event and also set which portion would be printed.

See the Example as below :

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript">
            function printthis() {
                var printthis = document.getElementById('printthis');
                var popupWin = window.open('', '_blank', 'width=1000,height=600');
                popupWin.document.open();
                popupWin.document.write('<html><body onload="window.print()">' + printthis.innerHTML + '</html>');
                popupWin.document.close();
            }
        </script>
    </head>
    <body>
        <div>
            Other contents
        </div>
        
        <div id="printthis">
            <div>
                Print this portion
            </div>
        </div>
        <div>
            <input type="button" value="print" onclick="printthis();" />
        </div>
    </body>
</html>

 

sometimes we want some portion of the page need to be print not a whole page,as per above example set id or class to portion which need to print (here #printthis).
when javascript function call on onclick then this function prints part of page which having data within #printthis div.

Slicebox : A fresh 3D image slider

Slicebox is a jQuery 3D image slider plugin that makes use of CSS 3D Transforms and provides a graceful fallback for older browsers that don’t support the new properties.

With the CSS 3D Transforms we can create some neat effects by transforming elements in three-dimensional space. Slicebox makes use of the 3D transforms properties and allows different kind of effects. The main idea is to create three-dimensional image slices that will rotate and reveal the next image as another side of the 3D object. In case the browser does not support 3D transforms, a simple slider will be used as fallback.

How to Use ?

In order to use Slicebox, put your images in an unordered list with the class “sb-slider”:

<ul id="sb-slider" class="sb-slider">

    <li>
        <a href="#" target="_blank">
            <img src="images/1.jpg" alt="image1"/>
        </a>
        <div class="sb-description">
            <h3>Creative Lifesaver</h3>
        </div>
    </li>

    <li>
        <img src="images/2.jpg" alt="image2"/>
        <div class="sb-description">
            <h3>...</h3>
        </div>
    </li>

    <li><!-- ... --></li>
    
    <!-- ... -->
    
</ul>

 

You can use the div with the class “sb-description” to add any kind of description for the respective image. As shown in this example, you can also add an anchor around the image.

Then you can call the plugin with:

$('#sb-slider').slicebox();

Options

$.Slicebox.defaults = {
	// (v)ertical, (h)orizontal or (r)andom
	orientation : 'v',

	// perspective value
	perspective : 1200,

	// number of slices / cuboids
	// needs to be an odd number 15 => number > 0 (if you want the limit higher, 
	// change the _validate function).
	cuboidsCount : 5,

	// if true then the number of slices / cuboids is going to be random (cuboidsCount is overwitten)
	cuboidsRandom : false,

	// the range of possible number of cuboids if cuboidsRandom is true
	// it is strongly recommended that you do not set a very large number :)
	maxCuboidsCount : 5,

	// each cuboid will move x pixels left / top (depending on orientation). 
	// The middle cuboid doesn't move. the middle cuboid's neighbors will 
	// move disperseFactor pixels
	disperseFactor : 0,

	// color of the hidden sides
	colorHiddenSides : '#222',

	// the animation will start from left to right. The left most 
	// cuboid will be the first one to rotate
	// this is the interval between each rotation in ms
	sequentialFactor : 150,

	// animation speed
	// this is the speed that takes "1" cuboid to rotate
	speed : 600,

	// transition easing
	easing : 'ease',

	// if true the slicebox will start the animation automatically
	autoplay : false,

	// time (ms) between each rotation, if autoplay is true
	interval: 3000,

	// the fallback will just fade out / fade in the items
	// this is the time fr the fade effect
	fallbackFadeSpeed : 300,
	
	// callbacks
	onBeforeChange : function( position ) { return false; },
	onAfterChange : function( position ) { return false; }
};

 

For more details and example visit www.tympanus.net/codrops

jQuery Display Progress Bar on Button Click in Asp.net

Default.aspx

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>jQuery show progress bar on button click asp.net</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<style type="text/css">
.sample
{
background-color:#DC5807;
border:1px solid black;
border-collapse:collapse;
color:White;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="DisableDiv"> </div>
<input type="button" id="btnClick" value="Get Data" />
<div id="testdiv"></div>
</form>
<script type="text/javascript">
$(function() {
$('#btnClick').click(function() {
$('#DisableDiv').fadeTo('slow', .6);
$('#DisableDiv').append('<div style="background-color:#E6E6E6;position: absolute;top:0;left:0;width: 100%;height:300%;z-index:1001;-moz-opacity: 0.8;opacity:.80;filter: alpha(opacity=80);"><img src="loading.gif" style="background-color:Aqua;position:fixed; top:40%; left:46%;"/></div>');
setTimeout(function() { GetData() }, 1000)
})
});
function GetData()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ShowLoadingImageonButtonClick.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function(data) {
var theHtml = data.d;
$('#testdiv').html(theHtml)
$('#DisableDiv').html("");
},
error: function(result) {
alert("Error");
}
});
}
</script>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string BindDatatable()
{
GridView gv = new GridView();
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("select UserId,UserName,Location from UserInformation", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
gv.HeaderStyle.CssClass = "sample";
gv.DataSource = dt;
gv.DataBind();
gv.RenderControl(htmlWriter);
return stringWriter.ToString();
}

 

jQuery Higlight Table Row & Column on Mouseover in Asp.net

Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title>Asp.net Bind Data to Datatable using JQuery or JSON</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.d.length; i++) {
if (i % 2 == 0) {
$("#tbDetails").append("<tr class=tg-even><td>" + data.d[i].Tagid + "</td><td>" + data.d[i].TagName + "</td><td>" + data.d[i].Noofarticles + "</td></tr>");
}
else {
$("#tbDetails").append("<tr><td>" + data.d[i].Tagid + "</td><td>" + data.d[i].TagName + "</td><td>" + data.d[i].Noofarticles + "</td></tr>");
}
}
$('td').mouseover(function() {
$(this).siblings().css('background-color', '#EAD575');
var ind = $(this).index();
$('td:nth-child(' + (ind + 1) + ')').css('background-color', '#EAD575');
});
$('td').mouseleave(function() {
$(this).siblings().css('background-color', '');
var ind = $(this).index();
$('td:nth-child(' + (ind + 1) + ')').css('background-color', '');
});
},
error: function(result) {
alert("Error");
}
});
});
</script>
<style type='text/css'>
.tbl {
border-collapse: collapse;
border-spacing: 0;
}
.tbl td, .tbl th {
background-color: #fff;
border: 1px #bbb solid;
color: #333;
font-family: sans-serif;
font-size: 100%;
padding: 10px;
vertical-align: top;
}
.tbl .tg-even td {
background-color: #eee;
}
.tbl th {
background-color: #ddd;
color: #333;
font-size: 110%;
font-weight: bold;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<table id="tbDetails" class="tbl">
<tr >
<th>UserId</th>
<th>UserName</th>
<th>Location</th>
</tr>
<tbody>
</tbody>
</table>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]
public static UserDetails[] BindDatatable()
{
List<UserDetails> details = new List<UserDetails>();
DataTable dt = new DataTable();
dt.Columns.Add("Tagid", typeof(Int32));
dt.Columns.Add("TagName", typeof(string));
dt.Columns.Add("Noofarticles", typeof(string));
dt.Rows.Add(1, "Asp.Net", 100);
dt.Rows.Add(2, "C#.Net", 10);
dt.Rows.Add(3, "SQL Server", 30);
dt.Rows.Add(4, "jQuery", 20);
dt.Rows.Add(6, "javascript", 15);
dt.Rows.Add(7, "XSLT", 50);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Tagid = dtrow["Tagid"].ToString();
user.TagName = dtrow["TagName"].ToString();
user.Noofarticles = dtrow["Noofarticles"].ToString();
details.Add(user);
}
return details.ToArray();
}
public class UserDetails
{
public string Tagid { get; set; }
public string TagName { get; set; }
public string Noofarticles { get; set; }
}
}

 

 

Slider with Slideshow (jQuery)

1. Javascript Code

<!-- it works the same with all jquery version from 1.x to 2.x -->
<script src="jquery.min.js"></script>
<script src="jssor.slider.mini.js"></script>
<script>
    jQuery(document).ready(function ($) {
        //Define an array of slideshow transition code
        var _SlideshowTransitions = [
        { code1 },
        { code2 },
        { code3 }
        ];
        var options = {
            $AutoPlay: true,
            $SlideshowOptions: {
                    $Class: $JssorSlideshowRunner$,
                    $Transitions: _SlideshowTransitions,
                    $TransitionsOrder: 1,
                    $ShowLink: true
                }
        };
        var jssor_slider1 = new $JssorSlider$('slider1_container', options);
    });
</script>

 2. HTML code

<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px; height: 300px;">
    <!-- Slides Container -->
    <div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; width: 600px; height: 300px;">
        <div><img u="image" src="image1.jpg" /></div>
        <div><img u="image" src="image2.jpg" /></div>
    </div>
</div>

 

Ajax Upload and Resize an Image with PHP.

Today I am presenting the most important social networking feature called ajax upload and resize an image without refreshing the page using jquery and PHP. This tutorial a continuation of my previous post, I just included image re-sizing function for different dimensions. It is very useful for your web project that saves lots of hosting space and bandwidth limit. Take a quick look at the live demo.

admin-ajax

The tutorial contains three folders called js,includes and uploads with PHP files.
includes
— getExtension.php
— compressImage.php
js
— jquery.min.js
— jquery.form.js
uploads
index.php
ajaximageupload.php
db.php

Javascript Code

$(“#photoimg”).live(‘change’,function(){})- photoimg is the ID name of INPUT FILE tag and $(‘#imageform’).ajaxForm() – imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.

<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{ 

$('#photoimg').live('change', function() 
 {
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");

$("#imageform").ajaxForm({target: '#preview', 
beforeSubmit:function(){
A.show();
B.hide();
}, 
success:function(){
A.hide();
B.show();
}, 
error:function(){
A.hide();
B.show();
} }).submit();
});

}); 
</script>

Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.

index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value. 

<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image: 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />

</div>
</form>

Sample database design for Users.

Users
Contains user details username, password, email and profile_image  etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200)
)

ajaximage.php

Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention

<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
include_once 'includes/getExtension.php';
$imagename = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($imagename))
{
$ext = strtolower(getExtension($imagename));
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$uploadedfile = $_FILES['photoimg']['tmp_name'];

//Re-sizing image. 
include 'includes/compressImage.php';
$widthArray = array(200,100,50); //You can change dimension here.
foreach($widthArray as $newwidth)
{
$filename=compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth);
echo "<img src='".$filename."' class='img'/>";
}

//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{
//Insert upload image files names into user_uploads table
mysqli_query($db,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id';");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB"; 
}
else
echo "Invalid file format.."; 
}
else
echo "Please select image..!";
exit;
}
?>

compressImage.php
Re-sizing image into different pixel dimensions. 

<?php
function compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth)
{

if($ext=="jpg" || $ext=="jpeg" )
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext=="png")
{
$src = imagecreatefrompng($uploadedfile);
}
else if($ext=="gif")
{
$src = imagecreatefromgif($uploadedfile);
}
else
{
$src = imagecreatefrombmp($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $path.$newwidth.'_'.$actual_image_name; //PixelSize_TimeStamp.jpg
imagejpeg($tmp,$filename,100);
imagedestroy($tmp);
return $filename;
}
?>

getExtension.php
This extracts file extension. 

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

db.php
Database configuration file, modify username, password and database values. 

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 

Auto Load and Refresh Div every 10 Seconds with jQuery

Have you seen this Twitter Search and Facebook shows most recent tweets/posts count from the database every 10 seconds on top of the page. I had developed like this with jQuery and Ajax. It’s simple just 5 lines of code

Example 1

Index.html
Contains javascript and HTML code. Take a look at load(“record_cound.php”)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds

<body>
<div id="load_tweets"> </div>
</body>

</script>

record_count.php
Just printing “9lessons | programming” every 10 seconds

<?php
echo "9lessons | Programming blog..............";
?>

Example 2

index.php
Contains PHP code you have to pass the search box value twitter.com/search?q=”some thing” to $search_word in facebook pass the user id or user session value.

 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $search_word; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds

<body>
<div id="load_tweets"> </div>
</body>

</script>

 

record_count.php
Counting tweets/posts from the database.

<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select id form Messages where message 
LIKE '%$search_word%'");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $record_count;
?>

db.php
Database configuration file, modify username, password and database values. 

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 

 

Ajax PHP Login Page with Shake Animation Effect.

how to create Ajax PHP login script, in this post I want to discuss how to create a simple Ajax PHP login with welcome page using MySQL database. This will explain you creating user tables, posting form values and storing and destroying the session values. If you are a PHP beginner take a quick look at this live demo with Username: 9lessons Password:9lessons. This post has been updated with mysqli.

Users Table
User table contains all the users registration details. 

CREATE TABLE `users` (
`uid` INT(11) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(45) ,
`password` VARCHAR(100) ,
`email` VARCHAR(45) ,
`friend_count` INT(11) ,
`profile_pic` VARCHAR(150),
PRIMARY KEY (`uid`));

Jquery Code
Contains javascipt code, $(“#login”).click(function(){}– login is the ID name of the login button. Using element.val() calling username and password input values. If id value is even number if(id(even) % 2) = If(0) false

<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() 
{

$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
$("body").load("home.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "home.php";
}
else
{
//Shake animation effect.
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});

}
return false;
});

});
</script>

index.php
Contains PHP and HTML code, If session value exists this will  redirect to home page.

<?php
session_start();
if(!empty($_SESSION['login_user']))
{
header('Location: home.php');
}
?>
//HTML Code
<div id="box">
<form action="" method="post">
Username
<input type="text" class="input"  id="username"/>
Password
<input type="password" class="input"  id="password"/>
<input type="submit" class="button button-primary" value="Log In" id="login"/>
<div id="error"></div> 
</div>
</form> 
</div>

ajaxLogin.php
Contains PHP code, this will verify username and password values in database.

<?php
include("db.php");
session_start();
if(isset($_POST['username']) && isset($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($db,$_POST['username']); 
//Here converting passsword into MD5 encryption. 
$password=md5(mysqli_real_escape_string($db,$_POST['password'])); 

$result=mysqli_query($db,"SELECT uid FROM users WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $username and $password, table row  must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid']; //Storing user session value.
echo $row['uid'];
}

}
?>

home.php
If user session value is empty, this will redirect to login page.
<?php
session_start();
if(empty($_SESSION['login_user']))
{
header('Location: index.php');
}
?>
//HTML Code
Welcome to Home Page
<a href="logout.php">Logout</a>

logout.php
Cleaning the user session value.

<?php
session_start();
if(!empty($_SESSION['login_user']))
{
$_SESSION['login_user']='';
session_destroy();
}
header("Location:index.php");
?>

db.php
Database configuration file, modify username, password and database values. 

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>