Skip to main content

Posts

Showing posts from 2012

Ajax Database

To clearly illustrate how easy it is to access information from a database using Ajax, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, lets do ground work. Create a table using the following command. NOTE: We are asuing you have sufficient privilege to perform following MySQL operations CREATE TABLE `ajax_example` ( `name` varchar(50) NOT NULL, `age` int(11) NOT NULL, `sex` varchar(1) NOT NULL, `wpm` int(11) NOT NULL, PRIMARY KEY (`name`) ) Now dump the following data into this table using the following SQL statements INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20); INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44); INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87); INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72); INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0); INSERT INTO

Image Map in javascript

You can use JavaScript to create client side image map. Client side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags. The image that is going to form the map is inserted into the page using the <img /> element as normal, except it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign. The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use. The <area> element specifie

Redirect a page in javascript

What is page redirection ? When you click a URL to reach to a page X but internally you are directed to another page Y that simply happens because of page re-direction. This concept is different from JavaScript Page Refresh. There could be various reasons why you would like to redirect from original page. I'm listing down few of the reasons: You did not like the name of your domain and you are moving to a new one. Same time you want to direct your all visitors to new site. In such case you can maintain your old domain but put a single page with a page re-direction so that your all old domain visitors can come to your new domain. You have build-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server side page redirection you can use client side page redirection to land your users on appropriate page. The Search Engines may have already indexed your pages. But while moving to another domai

Print a page in javascript

Many times you would like to give a button at your webpage to print out the content of that web page via an actual printer. JavaScript helps you to implement this functionality using print function of window object. The JavaScript print function window.print() will print the current web page when executed. You can call this function directly using onclick event as follows: <head> <script type="text/javascript"> <!-- //--> </script> </head> <body> <form> <input type="button" value="Print" onclick="window.print()" /> </form> </body> This will produce following button which let you print this page. This serves your purpose to get page printed out, but this is not a recommended way of giving printing facility. A printer friendly page is really just a page with text, no images, graphics, or advertising. You can do one of the followings to make a page printer friendly: Mak

Form Validation in JavaScript

Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. If some of the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process and over burdening server. JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions. Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that required it. This would need just loop through each field in the form and check for data. Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This would need to put more logic to test correctness of data. We will ta

Error Handling in JavaScript

There are three types of errors in programming: (a) Syntax Errors and (b) Runtime Errors (c) Logical Errors: Syntax errors: Syntax errors, also called parsing errors, occur at compile time for traditional programming languages and at interpret time for JavaScript. For example, the following line causes a syntax error because it is missing a closing parenthesis: <script type="text/javascript"> <!-- window.print(; //--> </script> When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and code in other threads gets executed assuming nothing in them depends on the code containing the error. Runtime errors: Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). For example, the following line causes a run time error because here syntax is correct but at run time it is trying to call a non existed method: <script type="text/

Difference Between GET and POST methods

GET: 1) Data is appended to the URL. 2) It is a single call system. 3) Maximum data that can be sent is 256. 4) Data transmission is faster. 5) This is the default method for many browsers.  6) GET method have not security because of data view in address bar. For ex: we can not use this method for checking log in. 7) We can bookmark link with this method. 8) Server can log all action. 9) because of server log, we can pass 255 char. as query  string. 10) It can store only 18 form variable. POST: 1) Data is not appended to the URL. 2) It is a two call system. 3) There is no Limit on the amount of data.That is characters any amount of data can be sent. 4) Data transmission is comparatively slow. 5) No default and should be Explicitly specified. 6) We can not bookmark page link. 7) We can pass unlimited data by this method as query string. 8) It is more secure but slower as compared to GET. 9) POST form contents are passed to the script as an input file.

How To Optimize Your Site With GZIP Compression

Compression is a simple, effective way to save bandwidth and speed up your site. I hesitated when recommending gzip compression when speeding up your javascript because of problems in older browsers . But it's the 21st century. Most of my traffic comes from modern browsers, and quite frankly, most of my users are fairly tech-savvy. I don't want to slow everyone else down because somebody is chugging along on IE 4.0 on Windows 95. Google and Yahoo use gzip compression. A modern browser is needed to enjoy modern web content and modern web speed -- so gzip encoding it is. Here's how to set it up. Wait, wait, wait: Why are we doing this? Before we start I should explain what content encoding is. When you request a file like http://www.yahoo.com/index.html , your browser talks to a web server. The conversation goes a little like this: 1. Browser: Hey, GET me /index.html 2. Server: Ok, let me see if index.html is lying around... 3. Server: Found it!

Life cycle of Servlet

The life cycle of a servlet can be categorized into four parts: Loading and Inatantiation:  The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet. Initialization:  After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet. The servlet will be available for service if it

Methods of Servlets

A Generic servlet contains the following five methods: init() public void init(ServletConfig config) throws ServletException The  init() method  is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service.  The servlet cannot be put into the service if  The init() method does not return within a fix time set by the web server.   It throws a ServletException Parameters - The init() method takes   a  ServletConfig  object that contains the initialization parameters and servlet's configuration and throws a  ServletException  if an exception has occurred. service() public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects jav

Servlet Container

A servlet container is nothing but a compiled, executable program. The main function of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process. A container handles large number of requests as it can hold many active servlets, listeners etc. It is interesting to note here that the container and the objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are being handled by the container due to the entrance of more than one thread to an object at a time. Note : A Servlet container may run stand alone i.e. without a web server or even on another host. We can categorize the servlet containers as: I. A simple servlet container is not fully functional and therefore it can only run very simple s

What is Java Servlets?

Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent.  This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases.  Servlets can also access a library of HTTP-specific calls, receive all the benefits of

Table to jqGrid

In order to use this module you should mark the Table to Grid (in Other modules) when you download the grid. Calling Convention: tableToGrid ( selector , options ) This is function and not a method where selector(string) can be either the table's class or id options is array with grid options The html table should have the following structure: < table class = "mytable" > (or < table id = "mytable" > ) < tr > < th > header 1 < / th > < th > header 2 < / th > ... < / tr > < tbody > < tr > < td > data 1 < / td > < td > data 1 < / td > ... < / tr > < tr > ... < / tr > .... < / tbody > < table >

How to save JQGrid parameters in cookie

jqGrid is an excellent jquery plugin to display a grid. We added some filter possibilities and with jquery updated the url where we had to fetch the data from. Worked nice, however, when the user selected a certain filtering or a certain page and clicked on one of the items in the list, they were navigated away from the grid. When they navigated back, the grid was at its start position, so at the first page, default sorting and filtering. So we had to store the values selected by the user. I created two javascript functions for this (in combination with jQuery) function saveGridToCookie(name, grid) { var gridInfo = new Object(); name = name + window.location.pathname; gridInfo.url = grid.jqGrid( 'getGridParam' , 'url' ); gridInfo.sortname = grid.jqGrid( 'getGridParam' , 'sortname' ); gridInfo.sortorder = grid.jqGrid( 'getGridParam' , 'sortorder' ); gridInfo.s

onSelectRow event in jqgrid

The example below specifies the action to take when a row is selected.   var lastSel; jQuery ( "#gridid" ) . jqGrid ( { ... onSelectRow : function ( id ) { if ( id && id !== lastSel ) { jQuery ( '#gridid' ) . restoreRow ( lastSel ) ; lastSel = id; } jQuery ( '#gridid' ) . editRow ( id , true ) ; } , ... } ) ;

Multiple $(document).ready()

One more great thing about $(document).ready() that I didn't mention in my previous tutorial is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your JavaScript file with them. It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free. You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so: <script src="/scripts/jquery.js"></script> <script src="/scripts/common.js"></script> <script src="/scripts/homepage.js"></script> You could also do something like this inside a sin

Introducing $(document).ready()

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. $(document).ready(function() { // put all your jQuery goodness in here. });   The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML. You can separate all of your JavaScript/jQuery into a separate file where it's easier to maintain and where it can stay out of the way of the content. I never did like seeing all those "javascript:void()" messages in the status bar when I would hover over a link. That's what happens when you attach the event directly inside an <a href> tag. On some pages that use traditional JavaScript, you'll see an "onloa

JQGrid Custom Validation

How to check whether EmailId already exists or not colModel:[{name:'emailId',index:'emailId', width:200,editable:true, sorttype:'int',editrules:{email:true, required:true, custom:true, custom_func:checkvalid}}], function checkvalid(value, colname) {                                              var gr = jQuery("#list2").getGridParam('selarrrow');       if(gr=='')       {             var flag = false;             var allRowsInGrid=$("#list2").getGridParam("records");             for(i=1;i<=allRowsInGrid;i++)             {                  var rowId = $("#list2").getRowData(i);                  var emailId = rowId['emailId'];                  if(emailId == value)                  {                        flag = true;                  }             }             if(flag == true)                  return [false,"Email Id: Email already exist, Please enter a different email ID."];    

jQuery to Simple Image Scroller

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us"> <head> <title>jCarousel Examples</title> <link href="../style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="script/jquery-1.2.3.pack.js"> </script> <script type="text/javascript" src="script/jquery.jcarousel.pack.js"> </script> <link rel="stylesheet" type="text/css" href="style/jquery.jcarousel.css"/> <link rel="stylesheet" type="text/css" href="style/skin.css" /> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('#mycarousel').jcarousel({ }); }); </script>

jQuery To Simple tabs

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>Tabs</title> <script src="script/jquery-1.1.3.1.pack.js" type="text/javascript"></script> <script src="script/jquery.history_remote.pack.js" type="text/javascript"></script> <script src="script/jquery.tabs.pack.js" type="text/javascript"></script> <script type="text/javascript"> $(function() {

jQuery Drop Down Menu

Steps to develop the Drop Down menu . Step 1:   Create a new file (suckerfish.html) and add the following code into it: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>jQuery  Drop Down Menu</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#van-one li").hover( function(){ $("ul", this).fadeIn("slow"); }, function() { } ); if (document.all) { $("#van-one li").hoverClass ("sfHover"); } }); $.fn.hoverCl

jQuery Toggle the Div

Steps to develop the Toggle of a Div . Step 1: Create a new file (jqrycollapse.html) and add the following code into it: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>JQuery Collapse</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(function() { $("#click_here").click(function(event) { event.preventDefault(); $("#div1").slideToggle(); }); $("#div1 a").click(function(event) { event.preventDefault(); $("#div1").slideUp();

JQuery Sliding elements example

For sliding effect jQuery has following methods : .slideDown( ) This method display the matched elements with a sliding effect. Example : Image is initially hidden, we can show it slowly : $('#clickme').click(function() {   $('#imageNew').slideDown('slow', function() {   // Animation complete.   }); }); .slideToggle( ) This method is used to display or hide the matched element with sliding effect. .slideUp( ) This method is used to hide the element with sliding effect. Example(for slideToggle & slideUp) : In the below example, when you click on given button, a window opens .And if you again click on this button, it hides window. This window also contain a '[x]' button. When you click on it, it hides the window also. This window displays because the button click fires 'slideToggle' event, which slide u

How to add Horizontal Scroll bar and checkbox in JQGrid

                                                 autowidth:true,                                                  scrollable:true,                                                  shrinkToFit:false,                                                  autoheight:true,                                                  multiselect: true,                                          

On Change Event in JQGrid

colModel:[ {name:'countryName',index:'countryName',width:100,editable:true,edittype:"select", editoptions:{value:countrylist, dataEvents :[                                                             { type: 'change', fn: function(e)                                                                 {                                                                     var thisval = $(e.target).val();                                                                     $.get('state.htm?id='+thisval,                                                                                       function(data)                                                                     {                                                                         var res = $(data).html();                                                                         $("#stateName").html(res);                                                                     })

Passing data to the Server

Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method. Example: This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it: <html> <head> <title>the title</title> <script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("#driver").click(function(event){ var name = $("#name").val(); $("#stage").load('/jquery/result.php', {"name":name} ); }); }); </script> </head> <body> <p>Enter your name and click on the button:</p> &l

Getting JSON data

There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action. Syntax: Here is the simple syntax for getJSON() method: [selector]. getJSON( URL, [data], [callback] ); Here is the description of all the parameters: URL: The URL of the server-side resource contacted via the GET method. data: An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. callback: A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second. Example: Consider the following HTML file with a small JQuery coding: <html> <head> <