Recently came across a beautiful client side validation language. Very powerful and effective. Specially it makes life easy when it comes to AJAX. Listing some of the use full example in jquery. Will keep on adding more as an when come across different problems. For more detail about JQuery visit the site 1) http://jquery.com/ 2) http://jquery.bassistance.de/api-browser
A: Jquery is very powerful language for doing Java script validation inline. For all the Non IDE developer, it makes life very easy. You just have to add appropriate classes in your tag for validation and call validate method on document load. Also you can define your own custom validation. Below is some of example. //Validation using classes //Step 1: Include necessary script files <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> //Step 2: define validate method on document ready. <script type="text/javascript"> $(document).ready(function(){ $("#recordCreate").validate(); }); //this is just a date picker UI. $(function() { $('.date-pick').datepicker(); }); </script> //For date picker add <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.datepicker.js"></script> //Step 3: Add styles for error display <style type="text/css"> * { font-family: Verdana; font-size: 96%; } label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> //Spep 4: Add classes in your form <form action="Chart/CreateChart" method="post" id="recordCreate" name="recordCreate"> <div id="chartForm"> <table align="center"> <tr> <td>Please Select Date:</td> <td><input type="text" id="date" name="date" class="date-pick required"> <font color="red">*</font> </td> </tr> <tr> <td>Please Select Level:</td> <td> <select name="level"> <option value="1">Level 1</option> <option value="2">Level 2</option> <option value="3">Level 3</option> </select> </td> </tr> <tr> <td>New Defect for this Month:</td> <td><input type="text" name="newDefects" class="digits"></td> </tr> <tr> <tr> <td>Number of Defect Resolved:</td> <td><input type="text" name="resolved" class="digits"></td> </tr> <tr> <td>Yield</td> <td><input type="text" name="yield" class="number"></td> </tr> <tr> <td>Median Resolution Time</td> <td><input type="text" name="median" class="number"></td> </tr> <tr> <td>Span:</td> <td><input type="text" name="span" class="number"></td> </tr> <tr></tr> <tr><td></td> <td><input type="submit" value="Create Entry"></td> </tr> <tr></tr> </table> </div> </form> Custom Validation Example //Step 1: Include necessary script files <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> //Step 2: define validate method on document ready. <script type="text/javascript"> $(document).ready(function(){ $("#recordCreate").validate({ rules: { newDefects: { digit: true }, resolved: { digit: true }, yield: { number: true }, median: { number: true }, span: { number: true } }, message: { newDefects: "Please enter only whole number." } }); //this is just a date picker UI. $(function() { $('.date-pick').datepicker(); }); </script> //For date picker add <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.datepicker.js"></script> //Step 3: Add styles for error display <style type="text/css"> * { font-family: Verdana; font-size: 96%; } label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> //Step 4:no need for class tag in above form for validation. Validation would be performed on name tag. <form action="Chart/CreateChart" method="post" id="recordCreate" name="recordCreate"> <div id="chartForm"> <table align="center"> <tr> <td>Please Select Date:</td> <td><input type="text" id="date" name="date" class="date-pick"> <font color="red">*</font> </td> </tr> <tr> <td>Please Select Level:</td> <td> <select name="level"> <option value="1">Level 1</option> <option value="2">Level 2</option> <option value="3">Level 3</option> </select> </td> </tr> <tr> <td>New Defect for this Month:</td> <td><input type="text" name="newDefects"></td> </tr> <tr> <tr> <td>Number of Defect Resolved:</td> <td><input type="text" name="resolved"></td> </tr> <tr> <td>Yield</td> <td><input type="text" name="yield"></td> </tr> <tr> <td>Median Resolution Time</td> <td><input type="text" name="median"></td> </tr> <tr> <td>Span:</td> <td><input type="text" name="span"></td> </tr> <tr></tr> <tr><td></td> <td><input type="submit" value="Create Entry"></td> </tr> <tr></tr> </table> </div> </form> Writing your own validation method jQuery.validator.addMethod( "selectNone", function(value, element) { if (element.value == "none") { return false; } else return true; }, "Please select an option." ); $(document).ready(function() { $("#form2").validate({ rules: { sport: { selectNone: true } }, }); }); We do so by calling the jQuery.validator.addMethod() method. It takes three parameters: name: The name of the method, used to identify and referencing it, must be a valid javascript identifier. method: the actual method implementation, returning true if an element is valid. message: The default message to display for this method. In the validate function, we specify that the 'sport' field should be validated using the selectNone method. For more detail about Validation UI in Jquery Please refer http://docs.jquery.com/Plugins/Validation ^ TOP A: There are many ways through which JQuery Ajax can work. We will see each one of them, Please note that these request will work if it is made through same domain. Different domain Ajax request is handled differently. Option 1: Using Load format: load(url,data,callback) Description: Load HTML from a remote file and inject it into the DOM.
Step 1: Create page that needs to be loaded say "example.html" < ul id = "favoriteMovies" > 02. < li style = "font-weight: bold; list-style-type: none;" >My Favorite Movies</ li > 03. < li >Contact</ li > 04. < li >Shawshank Redemption</ li > 05. < li >Napoleon Dynamite</ li > 06. < li >Back To The Future</ li > 07. < li >The Goonies</ li > 08. < li >Cinderella Man</ li > 09. < li >Apollo 13</ li > 10. </ ul > Step 2: Define page where it needs to be loaded 1. < div id = "container" > 2. < a href = "#" id = "loadData" >Click This Link To Load My Favorite Movies</ a > 3. </ div > Step 3: Define load method in jquery 01. $(document).ready( function () 02. { 03. $( "#loadData" ).click( function () 04. { 05. $( this ).text( "...One Moment Please..." ); 06. $( "#container" ).append( '<div id="favoriteMovies"></div>' ) 07. .children( "#favoriteMovies" ).hide() 08. .load( "example.html ul#favoriteMovies" , function () 09. { 10. $( "#loadData" ).remove(); 11. $( "#favoriteMovies" ).slideDown( "slow" ); 12. }); 13. return false ; 14. }); 15. }); Based on parameter server decides to go with either get or post request for data. So using load won't insure whether caching will be performed or not, it is entirely up to browser. Option 2: Using Get format: $.get(url,parameters,callback,type) description: Initiates a GET request to the server using the specified URL with any passed parameters as the query string. Arguments:
Example:
problem with get method is, some time it won't work with IE6 or IE7. If Data is in form of JSON response, we can use $.getJSON Format: jQuery. Option 3: Using POST Format: jQuery.getJSON(url,[data],[callback]) description: Load JSON data using an HTTP GET request. As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONPcallback, which can be done like so: "myurl?callback=?". (The other domain needs to support JSON-P output.) jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. This callback parameter may vary depending on API, for instance Yahoo Pipes requires "_callback=?" Arguments:
Example: <html>Option 3: Using Post There are any number of reasons why we might choose a POST over a GET. First, the intention of the HTTP protocol is that POST will be used for any nonidempotent requests. Therefore, if our request has the potential to cause a change in the server-side state, it should be a POST (at least according to HTTP purists). Accepted practices and conventions aside, a POST operation must sometimes be used when the data to be passed to the server exceeds the small amount that can be passed by URL in a query string; that limit is a browser-dependent value. And sometimes, the server-side resource we contact may only support POST operations, or it might even perform different functions depending upon whether our request uses the GET or POST method. For those occasions when a POST is desired or mandated, jQuery offers the $.post() utility function, which operates in the exact same fashion as $.get() except for the HTTP method used. Between the load() command and the various GET and POST jQuery Ajax functions, we can exert some measure of control over how our request is initiated and how we’re notified of its completion. But for those times when we need full control over an Ajax request, jQuery has a means for us to get as picky as we want. Format: jQuery.post(url, [data], [callback], [type]) description: Initiates a POST request to the server using the specified URL with any parameters passed within the body of the request. Example: Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). $.post("test.php", { name: "John", time: "2pm" }, Gets the test.php page content, store it in a XMLHttpResponse object and applies the process() JavaScript function. $.post("test.php", { name: "John", time: "2pm" }, Gets the test.php page contents which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>) $.post("test.php", { func: "getNameAndTime" }, Option 4: Using Ajax For those times when we want or need to exert a fine-grained level of control over how we make Ajax requests, jQuery provides a general utility function for making Ajax requests named $.ajax(). Under the covers, all other jQuery features that make Ajax requests eventually use this function to initiate the request. Its syntax is as follows: Format: $.ajax(options) Description: Initiates an Ajax request using the passed options to control how the request is made and callbacks notified. Looks simple, doesn’t it? But don’t be deceived. The options parameter can specify a large range of values that can be used to tune the operation of this function. Please click http://docs.jquery.com/Ajax/jQuery.ajax#options to get all the possible options Setting up Request: Format:$.ajaxSetup(properties) Description: Establishes the passed set of properties as the defaults for subsequent calls to $.ajax(). Parameters: properties (Object) An object instance whose properties define the set of default Ajax properties. These are the same properties described for the $.ajax() Example: $.ajaxSetup({ type: 'POST', timeout: 5000, dataType: 'html', error: function(xhr) { $('#errorDisplay) .html('Error: ' + xhr.status + ' ' + xhr.statusText); } }) Sets the defaults for AJAX requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following AJAX requests then sends some data without having to set anything else. $.ajaxSetup({ Ajax Global Functions ajaxStart(callback) ajaxSend(callback) ajaxSuccess(callback) ajaxError(callback) ajaxComplete(callback) ajaxStop(callback) Attaches the passed function to all matched elements invoked when the specified point in the processing of an Ajax request takes place. Parameters callback (Function) The callback function to be attached Examples: Show a loading message whenever an AJAX request starts (and none is already active). $("#loading").ajaxStart(function(){ Show a message before an AJAX request is sent. $("#msg").ajaxSend(function(evt, request, settings){Show a message when an AJAX request completes successfully. $("#msg").ajaxSuccess(function(evt, request, settings){ Show a message when an AJAX request fails. $("#msg").ajaxError(function(event, request, settings){ Show a message when an AJAX request completes. $("#msg").ajaxComplete(function(event,request, settings){Hide a loading message after all the AJAX requests have stopped. $("#loading").ajaxStop(function(){ Choosing between Load, Get, Post, Ajax For loading HTML content into DOM elements, the load() command provides an easy way to grab the content from the server and make it the content of any wrapped set of elements. Whether a GET or POST method is used is determined by whether data needs to be passed to the server or not. When a GET is required, jQuery provides the utility functions $.get() and $.getJSON(); the latter is useful when JSON data is returned from the server. To force a POST, the $.post() utility function can be used. When maximum flexibility is required, the $.ajax() utility function, with its ample assortment of options, lets us control most aspects of an Ajax request. All other Ajax features in jQuery use the services of this function to provide their functionality. To make managing the bevy of options less of a chore, jQuery provides the $.ajaxSetup() utility function that allows us to set default values for any frequently used options to the $.ajax() function (and to all of the other Ajax functions that use the services of $.ajax()). To round out the Ajax toolset, jQuery also allows us to monitor the progress of Ajax requests and associate these events with DOM elements via the ajaxStart(), ajaxSend(), ajaxSuccess(), ajaxError(), ajaxComplete(), and ajaxStop() commands. ^ TOP A: Use when you are not sure about getting latest pages. This will override default browser behavior of caching. Retrieve the latest version of an HTML page. $.ajax({ A: You can now getScript to dynamically load, and execute, remote scripts. This could be used to load in jQuery plugins or other code modules. <html> ^ TOP A: This is very interesting problem. And if you have web service from other domain that returns JSON. Then you can dynamically create a script tag and assign the src attr to location of web service. For example, the following URLS (web service calls) can be used to retrieve a list of all the images of Einstein on the web:
and: Your JSP page will look like this
When the button is clicked, we make the call to the JavaScript function, dynamicTag, which dynamically creates a <script> element. This script element has no src attribute, so we dynamically create one and we assign the src attribute's URL as a call to the web service, so that when the page is opened, the web service is automatically called.
We pass as a parameter to our web service the value the user supplied to the text box. We also specify that the output should be JSON in the parameters, and the name of the callback function that the thread of execution should pick up at when control is returned to the client. The callback function is as follows:
he JSONData object has a ResultSet format, which returns a separate object for each result that is returned. The object returns Title, Summary, Url, ClickUrl, RefererUrl, FileSize, FileFormat, Height, Width andThumbnail properties. So, for the first item in our ResultSet in the example, the properties would be returned as follows:
The application then dynamically creates an image and assigns the URL property as the src attribute. We loop through for the first 10 images displaying each to the page as follows: ^ TOP A: jQuery.browser.[browser options] returns boolean for current browser option. Available browser options are,
Alerts "this is safari!" only for safari browsers if ($.browser.safari) {Alerts "Do stuff for firefox 3" only for firefox 3 browsers. jQuery.each(jQuery.browser, function(i, val) {Set a CSS property to specific browser. jQuery.each(jQuery.browser, function(i) {Code to find type of browser <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" |