How to Work with jQuery validationEngine

In this tutorial I will describe how to integrate jquery validation engine in your application.jQuery provide a very awesome library to validate form.
jQuery validation engine is a JavaScript plugin aimed at the validation of form fields in the browser (IE 6-8, Chrome, Firefox, Safari, Opera 10). The plugin provides visually appealing prompts that grab user attention on the subject matter.

Validations range from email, phone, and URL, to more complex calls such as Ajax processing or custom JavaScript functions. Bundled with many locales, the error prompts can be translated into the language of your choice.

How to use:
Step1: Add jquery library.

1
2
3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" type="text/
javascript"></script>

Step 2: Include validationEngine JS library.

1
2
3
<script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>

Step 3: Include validationEngine CSS library.

1
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>

Step 4: Add class into field.There are many predefined class attribute for different validation type.

1
2
3
4
5
<form id="formID" method="post" action="submit.action">
    <input value="2010-12-01" class="validate[required,custom[date]]" type="text" name="date" id="date" />
</form>

Step 5: Instantiate validate Engine based on form id.
$(“#form.id”).validationEngine();

Result:

validateengine

Best Jquery Image Crop Library

The cropping is used to manipulation of uploded image.Cropping is one of the most used photo manipulation techniques and in this tutorial we take a look some of the most popular JavaScripts Image Cropping scripts.

1-imageareaselect:imgAreaSelect is a jQuery plugin for selecting a rectangular area of an image. It allows web developers to easily implement image cropping functionality, as well as other user interface features, such as photo notes (like those on Flickr).

2-uvumitools:This simplified tool gives your users the ability to create a selection area that can be used to crop an image live on your web site. This is an extremely useful too for any site that provides image hosting, for example.

3-Javascript Image Cropper UI:It has been developped by DHTMLGoodies.This script has all the basic features required for a perfect image cropping solution. It works by dragging a rectangle around the area you want to crop.

4-Kroppr:Kroppr is intended to allow users to manipulate the images available on a website. There are plenty of online image cropping scripts that are used to create avatars, scale or crop images, for photo resize and photo crop – but, on top of that, Kroppr offers image rotation and some other features without any plugin required (Flash or Java).

5-Javascript Image Cropper UI:The JavaScript image cropper UI allows the user to crop an image using an interface with the same features and styling as found in commercial image editing software, and is is based on the Prototype JavaScript framework and script.aculo.us.

6-Jcrop:Jcrop is the quick and easy way to add image cropping functionality to your web application. It combines the ease-of-use of a typical jQuery plugin with a powerful cross-platform DHTML cropping engine that is faithful to familiar desktop graphics applications.

How to create model window

In this tutorial, we will learn how to create popup box based on URL.The url can be seperate file or mvc based url.We will use window manager class to create model box.The open method takes class name,window id and content url as parametrs.

The source code is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
jQuery('#modellink').click(function(e) {
            WindowManager.open({
                'winId' : 'add-box',
                'addClass' : 'modal600',
                'title' : 'Add Team',
                'contentURL': jQuery(this).attr('data-url'),
                'data' : {},
                'type' : 'POST'
            });
        });

Flexi Grid With Parameters

Now we will discuss next phase of flexi gird, how to pass parameters and relode flexi grid.
In this totorail i will described how to add search/sorting fucntionalty.The flexi grid laready have sorting but if you want custom sort ,Eg.: If we want only those record display in flexi grid which has status completed.

To achive above objective we need to pass status as a parmater and bind again flexi grid with new result set.
I have assume you are aware of flexi grid basic fucntionality.You can read my Previous Post

Below are simple code:

Javascript code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
jQuery("#task_status").live('change', function()
	{

		var status = $('#task_status option:selected').text();
		if(status =='Select All') {
		status =''
		}
		 jQuery("#tasks-listing-grid").flexOptions({query: 'status='+status}).flexReload();

	});

tasks-listing-grid: This is the target div.
Parameters: {query: ‘status=’+status}
PHP code:

1
2
3
4
5
if(isset($post['query']) && !empty($post['query'])){
			parse_str($post['query'], $query);
		}

Simple Example of Flexi Grid with PHP

In this post we will learn how to use flexi grid with php. Flexi grid is very useful jquery plug-in for listing elements. It has many features like sorting, pagination and reloading. Flexi grid provides flexibility to the developer to add hooks with grid event. This is magical combination flexi grid with PHP. Flexi grid is open source project.

We will implement flexi grid with PHP in MVC pattern.
Below are simple steps to with full db script:

Step 1: First we will create a table into db.

1
2
3
4
5
6
7
8
9
10
11
12
13
CREATE TABLE IF NOT EXISTS `tbl_issues` (
  `ISSUEID` int(11) NOT NULL AUTO_INCREMENT,
  `issueName` varchar(255) NOT NULL
  PRIMARY KEY (`ISSUEID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
INSERT INTO `tbl_issues` (`ISSUEID`, `issueName`) VALUES
(10, 'issue3');

Step 2: fetch the data in model class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function getAssignedIssues($options){
 global $wpdb;
$page = ($options['page'] > 1) ? $options['page'] : 1;
  		 $offset = $options['rp'];
  		 $limit = ($page-1)*$offset;

		 switch($options['sortname']){

  			case 'issueName':
  			default:
  				$options['sortname'] = 'Issue.ISSUEID';
  			break;
  		}
  		$records = array();

  		$sql = "
  				SELECT
  					Issue.ISSUEID AS id,
  					Issue.issueName AS issueName,

  				FROM
  					tbl_issues";
					$countQuery = "select count(Issue.ISSUEID) from tbl_issues AS Issue";

					$sql .= " ORDER BY ".$options['sortname']." ".$options['sortorder']."
  		 		   LIMIT ". $limit .",".  $offset ."";

		$total = $wpdb->get_var($countQuery);
  		$records = $wpdb->get_results($sql, ARRAY_A);

		return array(
  				'page' => $page,
  				'total' => $total,
  				'records' => $records

  			);

  	}

Step 3:After fetching data from database,we will call model method into controller class and format the results according flexi grid format.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public function getIssues() {
		global $current_user;

		$data = $this->User->getAssignedIssues(array(
					'page' => isset($post['page']) ? intval($post['page']) : 1,
					'rp' => isset($post['rp']) ? intval($post['rp']) : 5,
					'sortname' => isset($post['sortname']) ? trim($post['sortname']) : '',
					'sortorder' => isset($post['sortorder']) ? trim($post['sortorder']) : 'ASC'
			));

		$response = array(
	        'page' => $data['page'],
	        'total' => $data['total'],
	        'rows' => array()
    	);

		foreach($data['records'] as $record){
			$response['rows'][] = array(
					'id'=> $record['id'],
					'cell' => array(
							'id' => $record['id'],
							'issueName' => $record['issueName']

						)
				);
		}

		$this->render_view(_default', array(
				'locals' => array(
						'response' => $response
					)
				));
				exit(0);

	}

Step 4: Now we will add css and js library file into head section of view.

1
2
3
4
5
<link rel='stylesheet' id='css-flexigrid-css'  href='http://localhost/test/css/flexigrid.css?ver=3.4.2' type='text/css' media='all' />
<script type='text/javascript' src='http://localhost/testjs/jquery.base64.js'></script>
<script type='text/javascript' src='http://localhost/test/js/flexigrid.js'></script>

Step 5: Create table for bind grid.

1
<table class="table table-bordered table-hover" style="display: non" id="issues-listing-grid"></table>

Step 6: After adding jquery and flexi grid js file in head part of view file. We will format grid layout. we will add below code in bottom of view file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//issue

		var issueListingGrid = null,
        issueListingGrid = jQuery("#issues-listing-grid").flexigrid({
            url : "<?php echo mvc_public_url(array('controller' => 'users', 'action' => 'getIssues.json')); ?>",
            dataType : 'json',
            striped : true,
            colModel : [{
                display : 'Issue Name',
                name : 'issueName',
                width : 185,
                sortable : true,
                align : 'left'
            }
			],
            showToggleBtn : false,
            rpOptions: [5,10, 15, 20, 30, 50], //allowed per-page values

            procmsg: 'Processing, Please wait ...',
            pagestat: 'Displaying {from} to {to} of {total} records',
            onSuccess:function(){
                //getChangesforTeam();

            },
            datacol: {                

				'completionPercentage': function(colval) {
                    return colval+'%';
                }
            },
            sortname : "issueName",
            sortorder : "asc",
            usepager : true,
            title : '<img class="icon" src="<?php echo get_stylesheet_directory_uri(); ?>/wp_home_page/images/table.png">&nbsp;Isuue List',
            useRp : true,
            rp : 5,
            showTableToggleBtn : true,
            width : 'auto',
            height : 'auto'
        });

Result:

flexigrid

Best Libraries of Javascript for Improve User Experience

Now we are developing web application for web 2.0.In this tutorial I will describe best javascript library for improve user experience with performance of web sites. JavaScript is provided great plugin and library for improve web application performance and provide a way to moderator to provide the great user experience to the end user.

Bootbox.js is a small JavaScript library which allows you to create programmatic dialog boxes using Twitter’s Bootstrap modals, without having to worry about creating, managing or removing any of the required DOM elements or JS event handlers.
Download

Bonsai is a graphics library which includes an intuitive graphics API and an SVG renderer. You can use Bonsai to create dynamic images and graphics for your website. These are rendered as SVG elements to scale properly for any screen or device.

Download

validate.js is a lightweight and free JavaScript form validation library. It is very useful javascript library for form validation which is inspired by CodeIgniter.

Download

retina.js is an open source script that makes it easy to serve high-resolution images to devices with retina displays.

Download

gmaps.js allows you to use the potential of Google Maps in a very simple way.

Download

Moment.js is a 5kb javascript date library for parsing, validating, manipulating, and formatting dates.

Download

How To Create Generalized Function For Jquery Template

Hi, In previous tutorial I was told you how to use jquery template . In this tutorial we will learn how to create a generalized function to handle all template request in jquery.Normally we are creating each function to handle for each request, but it’s not good practice for developer, Always our first aim to write an optimize code for application.
In this tutorial I will tell you how to write an optimize single jQuery function which will handle all your Jquery template request. We just pass parameters array in this function and get result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function getDetails(params) {
    teamId = jQuery('#active-team-id').val();
    jQuery.ajax({
        url: siteurl + params['targetUrl'],
        cache: false,
        dataType: "html",
        data: {
            action: params['action'],
            teamId: teamId,
            dataID: params['dataID'],
        },
        type: 'Post',
        success: function (response) {
            var $obj = "";
            $obj = jQuery.parseJSON(response);
            jQuery(params['divID']).empty();
            //alert(jQuery(params['divID']).html());

            jQuery(params['templateId']).tmpl($obj).appendTo(params['divID']);
            //jQuery("#loeSummary").tmpl($obj).appendTo("#loe-summary");

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
        }
    });
}

How to use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
params = {
    targetUrl: 'loe/getTestDetails/1/',
    action: 'loe_controller_getTestDetails',
    templateId: "#testDetails",
    divID: "#test-details",
    dataID: jQuery('#map-id').val()
}
//alert(jQuery('#active-team-id').val());


getDetails(params);

How to Integrate Bootsrap Model Box with Jquery Template

In This post I will tell you how to add jquery template in bootsrtap Model box.Normally we are using inline code to add model box functionality but now its old technique, now everything is changing, we are using now bootstrap model box and Jquery template plugin.We are not including library file of model box and jquery template , I understand you have to basic knowledge of Jquery template and Bootstrap model box.
Following are simple steps to integrate model box with jquery template.

Objective of Example: we are creating detail of attributes based on attribute id.

Step 1: Create bootstrap model box.

Step 1.1 : adding hyperlink for popup model box.

1
<a href='#changeHistoryModal' role='button' class='history-details' data-toggle='modal'>Click me </a>

Step 1.2: adding Model box HTMl layot in file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!-- Modal -->
<div id="changeHistoryModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Change History</h3>
  </div>
  <div class="modal-body">
    Hi I am body of model
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
</div>

Step 2: Integrating template in bootstrap model box.

Step 2.1: adding template in model box, So now step 1.1 code would be change as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!-- Modal -->
<div id="changeHistoryModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Change History</h3>
  </div>
  <div class="modal-body">
    <table class="table table-condensed table-striped table-hover extended-font" width="100%" id="history-details" cellspacing="1" >
                    <thead><tr class="error">
                            <th >Column Name</th>
                            <th >Origional Value</th>
                            <th >Modified Value</th>
							<th >Modified Date</th>
                        </tr></thead>
                    <tbody id="history-details-div"></tbody></table>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
</div>

Step 2.2: adding template layout:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- jQuery JS Tempalate Start for details  -->
   <script id="changeHistoryDetailsLog" type="text/x-jquery-tmpl">
        <tr class="success"><td>${columnName}</td>
            <td>${origionalValue}</td>
            <td>${modifiedValue}</td>
			<td>${creationDate}</td>
        </tr>
    </script>

Step 2.3:Fill the Json object in template and display in div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- jQuery JS Template Start for details  -->
   <script id="changeHistoryDetailsLog" type="text/x-jquery-tmpl">
        <tr class="success"><td>${columnName}</td>
            <td>${origionalValue}</td>
            <td>${modifiedValue}</td>
			<td>${creationDate}</td>
        </tr>
    </script>

Result

model box

How to Add Search Functionality in Dropdown List with Jquery Plugin

In this tutorial i will let you know how to create dropdown list with Rich UI. Normally HTML provide simple SELECT element to create dropdown list.
In this tutorial you will learn how to create dropdown list with search functionality with help of excellent ‘chosen’ jquery plugin, you can download Here.
Below are simple example to learn dropdown list with search functionality.
Step 1: First we will add library file of chosen plugin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<head>
  <style>
    .clearfix:after {
      content: "\0020";
      display: block;
      height: 0;
      clear: both;
      overflow: hidden;
      visibility: hidden;
    }
  </style>
  <link rel="stylesheet" href="chosen/chosen.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
  <script src="chosen/chosen.jquery.js" type="text/javascript"></script>
</head>

Step 2: Now we will add HTMl dropdown list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div>
        <select data-placeholder="Choose a Country..." class="chzn-select" style="width:350px;" tabindex="2">
          <option value=""></option>
          <option value="United States">United States</option>
          <option value="United Kingdom">United Kingdom</option>
          <option value="Afghanistan">Afghanistan</option>
          <option value="Zambia">Zambia</option>
          <option value="Zimbabwe">Zimbabwe</option>
        </select>
      </div>

Step 3: Finally call chosen library method to apply css and functionality on dropdown list.

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
  jQuery(document).ready(function(){
  $("#choDDL").chosen();
  $(".chzn-select-deselect").chosen({allow_single_deselect:true});
  });
  </script>

Step 4: Result :

search-dropdownlist

Simple Jquery Template Tutorial

In this tutorial I will described how to create simple template with help of jQuery template plugin.Jquery templating is very exciting and innovation tool of jQuery lovers. jQuery template plugin works only Json object.

Below are simple steps to create simple template.

Step 1:Add script source in head tag of file.

1
2
3
4
5
6
7
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>


Step 2: Create HTML file to display template:

1
2
3
<button id="showBtn">Show Result</button><br/>
<table><tbody id="resultList"></tbody></table>

Step 3: Create Simple Json object

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
  var movies = [
  { Fname: "Parvez", Lname: "alam", Age: "25" },
  { Fname: "Peeyush", Lname: "Sharma", Age: "18" },
  { Fname: "Ved", Lname: "Prakash", Age: "25" }
  ];
  </script>

Step 4: Add Java script code to render template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
var markup = "<tr><td colspan='2'>${Fname}</td><td>Released: ${Lname}</td><td>Director: ${Age}</td></tr>"

/* Compile markup string as a named template */
$.template( "movieTemplate", markup );

/* Render the named template */
$( "#showBtn" ).click( function() {
  $( "#resultList" ).empty();
  $.tmpl( "movieTemplate", movies ).appendTo( "#resultList" );
});
</script>