Sunday, March 27, 2011

JQuery-Ajax

Hi everybody...

We have been working on JQuery-Core, JQuery-DOM, JQuery-CSS-JavaScript and JQuery-Events-Effects yet. Here I am going to explain JQuery-Ajax.

Ok let's start...

6. Ajax

6.1 loadIfModified(String,Map,Function)
loadIfModified(String url, Map params, Function callback)
returns jQuery

Load HTML from a remote file and inject it into the DOM, only if it's been modified by the server.

Example:
$("#feeds").loadIfModified("feeds.html");
HTML:
<div id="feeds"></div>
Result:
<div id="feeds"><b>45</b> feeds found.</div>

6.2 load(String,Object,Function)
load(String url, Object params, Function callback) returns
jQuery

Load HTML from a remote file and inject it into the DOM.
Note: Avoid to use this to load scripts, instead use $.getScript. IE strips script tags when there
aren't any other characters in front of it.

Example:
$("#feeds").load("feeds.html");
HTML:
<div id="feeds"></div>
Result:
<div id="feeds"><b>45</b> feeds found.</div>

Example:
Same as above, but with an additional parameter and a callback that is executed when the data
was loaded.

$("#feeds").load("feeds.html",
 {limit: 25},
 function() { alert("The last 25 entries in the feed have been loaded"); }
);

6.3 serialize()
serialize() returns String

Serializes a set of input elements into a string of data. This will serialize all given elements.
A serialization similar to the form submit of a browser is provided by the
[http://www.malsup.com/jquery/form/ Form Plugin]. It also takes multiple-selects  into account,
while this method recognizes only a single option.

Example:
Serialize a selection of input elements to a string

$("input[@type=text]").serialize();
HTML:
<input type='text' name='name' value='John'/>
<input type='text' name='location' value='Boston'/>

6.4 ajaxStart(Function)
ajaxStart(Function callback) returns jQuery
Attach a function to be executed whenever an AJAX request begins and there is none already
active.

Example:
Show a loading message whenever an AJAX request starts (and none is already active).

$("#loading").ajaxStart(function(){
 $(this).show();
});

6.5 ajaxStop(Function)
ajaxStop(Function callback) returns jQuery

Attach a function to be executed whenever all AJAX requests have ended.

Example:
Hide a loading message after all the AJAX requests have stopped.

$("#loading").ajaxStop(function(){
 $(this).hide();
});

6.6 ajaxComplete(Function)
ajaxComplete(Function callback) returns jQuery

Attach a function to be executed whenever an AJAX request completes.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Example:
Show a message when an AJAX request completes.

$("#msg").ajaxComplete(function(request, settings){
 $(this).append("<li>Request Complete.</li>");
});

6.7 ajaxSuccess(Function)
ajaxSuccess(Function callback) returns jQuery

Attach a function to be executed whenever an AJAX request completes successfully.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Example:
Show a message when an AJAX request completes successfully.

$("#msg").ajaxSuccess(function(request, settings){
 $(this).append("<li>Successful Request!</li>");
});

6.8 ajaxError(Function)
ajaxError(Function callback) returns jQuery

Attach a function to be executed whenever an AJAX request fails.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.
A third argument, an exception object, is passed if an exception occured while processing the
request.

Example:
Show a message when an AJAX request fails.

$("#msg").ajaxError(function(request, settings){
 $(this).append("<li>Error requesting page " + settings.url + "</li>");
});

6.9 ajaxSend(Function)
ajaxSend(Function callback) returns jQuery

Attach a function to be executed before an AJAX request is sent.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Example:
Show a message before an AJAX request is sent.

$("#msg").ajaxSend(function(request, settings){
 $(this).append("<li>Starting request at " + settings.url + "</li>");
});

6.10 $.get(String,Map,Function)
$.get(String url, Map params, Function callback) returns
XMLHttpRequest

Load a remote page using an HTTP GET request.
This is an easy way to send a simple GET request to a server without having to use the more
complex $.ajax function. It allows a single callback function to be specified that will be executed
when the request is complete (and only if the response has a successful response code). If you
need to have both error and success callbacks, you may want to use $.ajax.

Example:
$.get("test.cgi");

Example:
$.get("test.cgi", { name: "John", time: "2pm" } );

Example:
$.get("test.cgi", function(data){
 alert("Data Loaded: " + data);
});
 
Example:
$.get("test.cgi",
 { name: "John", time: "2pm" },
 function(data){
   alert("Data Loaded: " + data);
 }
);

6.11 $.getIfModified(String,Map,Function)
$.getIfModified(String url, Map params, Function callback)
returns XMLHttpRequest

Load a remote page using an HTTP GET request, only if it hasn't been modified since it was last
retrieved.

Example:
$.getIfModified("test.html");

Example:
$.getIfModified("test.html", { name: "John", time: "2pm" } );

Example:
$.getIfModified("test.cgi", function(data){
 alert("Data Loaded: " + data);
});
 
Example:
$.getifModified("test.cgi",
 { name: "John", time: "2pm" },
 function(data){
   alert("Data Loaded: " + data);
 }
);

6.12 $.getScript(String,Function)
$.getScript(String url, Function callback) returns
XMLHttpRequest

Loads, and executes, a remote JavaScript file using an HTTP GET request.
Warning: Safari <= 2.0.x is unable to evaluate scripts in a global context synchronously. If you load
functions via getScript, make sure to call them after a delay.

Example:
$.getScript("test.js");

Example:
$.getScript("test.js", function(){
 alert("Script loaded and executed.");
});

6.13 $.getJSON(String,Map,Function)
$.getJSON(String url, Map params, Function callback) returns
XMLHttpRequest

Load JSON data using an HTTP GET request.

Example:
$.getJSON("test.js", function(json){
 alert("JSON Data: " + json.users[3].name);
});

Example:
$.getJSON("test.js",
 { name: "John", time: "2pm" },
 function(json){
   alert("JSON Data: " + json.users[3].name);
 }
);

6.14 $.post(String,Map,Function)
$.post(String url, Map params, Function callback) returns
XMLHttpRequest

Load a remote page using an HTTP POST request.

Example:
$.post("test.cgi");

Example:
$.post("test.cgi", { name: "John", time: "2pm" } );

Example:
$.post("test.cgi", function(data){
 alert("Data Loaded: " + data);
});

Example:
$.post("test.cgi",
 { name: "John", time: "2pm" },
 function(data){
   alert("Data Loaded: " + data);
 }
);

6.15 $.ajaxTimeout(Number)
$.ajaxTimeout(Number time) returns undefined

Set the timeout in milliseconds of all AJAX requests to a specific amount of time. This will make all
future AJAX requests timeout after a specified amount of time.
Set to null or 0 to disable timeouts (default).
You can manually abort requests with the XMLHttpRequest's (returned by all ajax functions)
abort() method.
Deprecated. Use $.ajaxSetup instead.

Example:
Make all AJAX requests timeout after 5 seconds.

$.ajaxTimeout( 5000 );

6.16 $.ajaxSetup(Map)
$.ajaxSetup(Map settings) returns undefined

Setup global settings for AJAX requests.
See $.ajax for a description of all available options.

Example:
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( {
 url: "/xmlhttp/",
 global: false,
 type: "POST"
} );
$.ajax({ data: myData });

6.17 $.ajax(Map)
$.ajax(Map properties) returns XMLHttpRequest

Load a remote page using an HTTP request.
This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions
that are often easier to understand and use, but don't offer as much functionality (such as error
callbacks).
$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to
manipulate directly, but it is available if you need to abort the request manually.
'''Note:''' If you specify the dataType option described below, make sure the server sends the
correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead
to unexpected problems in your script. See [[Specifying the Data Type for AJAX Requests]] for
more information.
Supported datatypes are (see dataType option):
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text, included script tags are evaluated.
"script": Evaluates the response as Javascript and returns it as plain text.
"json": Evaluates the response as JSON and returns a Javascript Object
$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the
request. These are all the key/values that can be used:
(String) url - The URL to request.
(String) type - The type of request to make ("POST" or "GET"), default is "GET".
(String) dataType - The type of data that you're expecting back from the server. No default: If the
server sends xml, the responseXML, otherwise the responseText is passed to the success
callback.
(Boolean) ifModified - Allow the request to be successful only if the response has changed since
the last request. This is done by checking the Last-Modified header. Default value is false, ignoring
the header.
(Number) timeout - Local timeout in milliseconds to override global timeout, eg. to give a single
request a longer timeout while all others timeout after 1 second. See $.ajaxTimeout() for global
timeouts.
(Boolean) global - Whether to trigger global AJAX event handlers for this request, default is true.
Set to false to prevent that global handlers like ajaxStart or ajaxStop are triggered.
(Function) error - A function to be called if the request fails. The function gets passed tree
arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an
optional exception object, if one occured.
(Function) success - A function to be called if the request succeeds. The function gets passed one
argument: The data returned from the server, formatted according to the 'dataType' parameter.
(Function) complete - A function to be called when the request finishes. The function gets passed
two arguments: The XMLHttpRequest object and a string describing the type of success of the
request.
(Object|String) data - Data to be sent to the server. Converted to a query string, if not already a

string. Is appended to the url for GET-requests. See processData option to prevent this automatic
processing.
(String) contentType - When sending data to the server, use this content-type. Default is
"application/x-www-form-urlencoded", which is fine for most cases.
(Boolean) processData - By default, data passed in to the data option as an object other as string
will be processed and transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send DOMDocuments, set this option to false.
(Boolean) async - By default, all requests are sent asynchronous (set to true). If you need
synchronous requests, set this option to false.
(Function) beforeSend - A pre-callback to set custom headers etc., the XMLHttpRequest is passed
as the only argument.

Example:
Load and execute a JavaScript file.

$.ajax({
 type: "GET",
 url: "test.js",
 dataType: "script"
})

Example:
Save some data to the server and notify the user once its complete.

$.ajax({
 type: "POST",
 url: "some.php",
 data: "name=John&location=Boston",
 success: function(msg){
   alert( "Data Saved: " + msg );
 }
});

Example:
Loads data synchronously. Blocks the browser while the requests is active. It is better to block
user interaction by other means when synchronization is necessary.

var html = $.ajax({
url: "some.php",
async: false
}).responseText;


Example:
Sends an xml document as data to the server. By setting the processData option to false, the
automatic conversion of data to strings is prevented.

var xmlDocument = [create xml document];
$.ajax({
 url: "page.php",
 processData: false,
 data: xmlDocument,
 success: handleResponse
});

Well...

We have learned some practical JQuery APIs so far. I'm going to join JQuery with Spring MVC including a very powerful JQuery Plugin (JQuery Grid) using JQuery Ajax and JSON(JavaScript Object Notation) in a simple sample in my next post. You should get expert enough on JQuery to get ready for that High-Tech sample. So review JQuery courses and samples as mach as you can please.



all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Saturday, March 19, 2011

Spring Internationalization And Themes

Hey...

Most of enterprise applications should support internationalization and themes. I mean they should prepare users to change the application language and also select a themplate or even customize it.Spring has a powerful features to support them. Here I am going to take a sample of spring internationalization and themes.

Application Specification
The sample application is an extension of spring security sample. A user can login to it then a list of users will be displayed and if he or she has administrator or power user role, can change selected user's current theme and language in edit mode. Take a look to the following picture.
Image 1

System has 3 themes:
  • Default(Gray) Theme: Gray background color
  • Green Theme: Green background color
  • Blue Theme: Blue background color
and 2 language available:
  • Default(United States)
  • Farsi
If user changes one of the available theme and language for selected user and if the selected user and current user are the same, the changes will be shown after saving othervise whenever the selected user login to system, he or she will see the changes. Take a look to following picture:
Image 2: after selecting blue theme and Farsi language


I added two more extera fields in User Entity (refer to spring security post). theme and locale:
@Entity
@Table(name = "tb_user")
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    Long id;

    @Column(name = "name")
    String name;

    @Column(name = "username")
    String username;

    @Column(name = "password", updatable = false)
    String password;

    @Column(name = "theme")
    String theme;

    @Column(name = "locale")
    String locale;

    @ManyToMany(targetEntity = Role.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
    @JoinTable(name = "tb_user_role", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "role_id")})
    @Fetch(org.hibernate.annotations.FetchMode.SUBSELECT)
    List<Role> roleList;

    @Column(name = "account_non_expired")
    boolean accountNonExpired;

    @Column(name = "account_non_locked")
    boolean accountNonLocked;

    @Column(name = "credentials_non_expired")
    boolean credentialsNonExpired;

    @Column(name = "enabled")
    boolean enabled;

...

So I will find the current theme and current language by current user. But if current user is ananymouse, the default theme and default language(United States) will be assumed.

Now it's the time to explain about spring internationalization and themes.

Spring Internationalization
First we should prepare some different languages property files with the same master name with language brief name in continue. For example if the master name is messages, for United States: messages_en and for Farsi: messages_fa. Then we should place the keys and their values in them. Take a look this:

messages_en:
user.name=name
user.username=username
user.password=password
user.theme=user custom theme
user.locale=user language
user.accountNonExpired=account non expired
user.accountNonLocked=account non locked
user.credentialsNonExpired=credentials non expired
user.enabled=enabled
user.authorities=user authorities

welcome=welcome

save=save
back=back
edit=edit
view=view details
add=insert
delete=delete
search=search

login=login
logout=logout

messages_fa:
user.name=نام کاربر
user.username=نام کاربري
user.password=کلمه عبور
user.theme=قالب جاري کاربر
user.locale=زبان جاري کاربر
user.accountNonExpired=حساب کاربری باطل نشده
user.accountNonLocked=حساب کاربری قفل نشده
user.credentialsNonExpired=اعتبار نامه کابر باطل نشده
user.enabled=فعال
user.authorities=اجازه های دسترسی کاربر


welcome=خوش آمدید


save=ذخیره
back=بازگشت
edit=ویرایش
view=نمایش جزئیات
add=افزودن
delete=حذف
search=جستجو


login=ورود
logout=خروج
and so on.
The next step is spring configuration. I make an xml file called internationalization-config.xml and import it in major spring configuration(spring-servlet.xml). Here is the configuration:
<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <beans:bean id="messageSource"
                class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="classpath:messages"/>
        <beans:property name="defaultEncoding" value="UTF-8"/>
    </beans:bean>
    <beans:bean id="localeResolver"
    class="com.internationalization.CustomLocaleResolver">
    <beans:property name="defaultLocale" value="en"/>
</beans:bean>
</beans:beans>
I should define a bean with "messageSource' id(the name should be this. it is a reserved id name) type of ReloadableResourceBundleMessageSource class. I choose resource bundle source via this bean. I determine the master name of the property file is messages with UTF-8 encoding.
Then I should define the localeResolver to determine current locale so I prepare CustomLocaleResolver for that. This class will find the current user and returns its current locale otherwise returns the default locale(United States). Every localeResolver classes should be instance of org.springframework.web.servlet.LocaleResolver interface. But there is a useful abstract class called "AbstractLocaleResolver" is an instance of LocaleResolver interface. It has good properties like "defaultLocale", so I extend CustomLocaleResolver class from AbstractLocaleResolver class. Here is the code:
public class CustomLocaleResolver extends AbstractLocaleResolver {

    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        User user = SecurityUtils.getCurrentUser();
        if (user != null && user.getLocale() != null && !user.getLocale().equals("")) {
            return new Locale(user.getLocale());
        } else {
            return Locale.US;
        }
    }

    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    }
}
SecurityUtils is an utility class which returns the current user from spring security. Here is the code:
public class SecurityUtils {
    public static User getCurrentUser(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = null;
        if (principal instanceof User) {
            user = (User) principal;
        }
        return user;
    }
}
after configuration I can use it in the pages. Spring has a tag to do it.
<spring:message code="key"/>
For example in user-edit.jsp I use this tag:
<form:form id="userForm">
    <form:hidden path="user.id"/>
    <table>
        <tr>
            <td><spring:message code="user.name"/> </td>
            <td><form:input path="user.name"/></td>
        </tr>
        <tr>
            <td><spring:message code="user.username"/> </td>
            <td><form:input path="user.username" autocomplete="false"/></td>
        </tr>
        <tr>
            <td><spring:message code="user.password"/> </td>
            <td><form:password showPassword="false" path="user.password" autocomplete="false"/></td>
        </tr>
        <tr>
            <td><spring:message code="user.theme"/> </td>
            <td><form:select path="user.theme">
                <form:option value="default" label="default"></form:option>
                <form:option value="green" label="green"></form:option>
                <form:option value="blue" label="blue"></form:option>
            </form:select></td>
        </tr>
...

</form:form>
another point is direction. Most middle east countries read from right to left(against Europeans and Americans). So I should change the main div direction when the current user language is Farsi. I do it in /WEB-INF/layout/view.jsp
<security:authentication property="principal" var="principal"/>
<c:set var="anonymousUser" value="${false}"/>
<security:authorize access="isAnonymous()">
    <c:set var="anonymousUser" value="${true}"/>
</security:authorize>
<c:choose>
   <c:when test="${!anonymousUser and principal.locale=='fa'}">
      <div class="mainDiv" dir="rtl"></c:when>
   <c:otherwise>
      <div class="mainDiv"></c:otherwise> 

</c:choose>
        <security:authorize access="isAuthenticated()">
            <a href="/j_spring_security_logout"><spring:message code="logout"/> </a><br/> <spring:message code="welcome"/> <security:authentication
                property="principal.name"/>
        </security:authorize>
        <tiles:insertAttribute name="body"/>
    </div>
I handle it by c:choose. When current user is ananymous or has United States locale, the main div direction should be left to right otherwise should be right to left.
spring:message looks like fmt:message jstl tag. we can set it to variable. Take a look to this:
<spring:message key="user.name" var="name"/>
${name}
As you can see in above sample you can have the variable in page scope and use it in EL.

Spring Theme
Spring Theme looks like Spring Internationalization both in configuration and usage.
First I should create an xml file called theme-config.xml for configuration and import it in main configuration file(spring-servlet.xml).
theme-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <beans:bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
        <beans:property name="basenamePrefix" value="theme-" />
    </beans:bean>

    <beans:bean id="themeResolver" class="com.theme.CustomThemeResolver">
        <beans:property name="defaultThemeName" value="default"/>
    </beans:bean>
</beans:beans>
I should define a bean with "themeSource' id(the name should be this. it is a reserved id name) type of ResourceBundleThemeSource class. I choose resource bundle source via this bean. I name the base name prefix to "theme-". So any property file which starts with "theme-" could be theme resource bundle. For example "theme-blue"
Then I should define the themeResolver to determine current theme so I prepare CustomThemeResolver for that. This class will find the current user and returns its current theme otherwise returns the default theme(default). Every localeResolver classes should be instance of org.springframework.web.servlet.ThemeResolver interface. But there is a useful abstract class called "AbstractThemeResolver" is an instance of ThemeResolver interface. It has good properties like "defaultThemeName", so I extend CustomThemeResolver class from AbstractThemeResolver class. Here is the code:
public class CustomThemeResolver extends AbstractThemeResolver {
    public static final String DEFAULT_THEME = "default";
    public static final String DEFAULT_GREEN = "green";
    public static final String DEFAULT_BLUE = "blue";

    public String resolveThemeName(HttpServletRequest request) {
        User user = SecurityUtils.getCurrentUser();
        if (user != null && user.getTheme() != null && !user.getTheme().equals("")) {
            return user.getTheme();
        } else {
            return DEFAULT_THEME;
        }
    }

    public void setThemeName(HttpServletRequest request, HttpServletResponse response, String s) {
    }
}
If I want to have 3 themes so I should have 3 property files.

theme-default.properties
css=/themes/default/main.css

theme-green.properties
css=/themes/green/main.css

theme-blue.properties
css=/themes/blue/main.css
these are the path of css classes. Any theme property should determine the path of the css file in css key.
As is shown in above there should be 3 folders in theme folder including: default, green and blue. Each folder should contains a main.css file.

/theme/default/main.css
.mainDiv{
    background-color:lightgray;
    padding:2px;
    margin:2px;
}

/theme/green/main.css
.mainDiv{
    background-color:lightgreen;
    padding:2px;
    margin:2px;
}

/theme/blue/main.css
.mainDiv{
    background-color:lightblue;
    padding:2px;
    margin:2px;
}

Now it's the time to use it in pages. Spring has a tag which return the value of the current theme key
<spring:theme code='key'/>
For example in /WEB-INF/layout/view.jsp file:
<html>
<head>
    <link rel="stylesheet" type="text/css" href="<spring:theme code='css'/>"/>
</head>
<body>
<security:authentication property="principal" var="principal"/>
<c:set var="anonymousUser" value="${false}"/>
<security:authorize access="isAnonymous()">
    <c:set var="anonymousUser" value="${true}"/>
</security:authorize>
<c:choose>
   <c:when test="${!anonymousUser and principal.locale=='fa'}">
      <div class="mainDiv" dir="rtl"></c:when>
   <c:otherwise>
      <div class="mainDiv"></c:otherwise>
   </c:choose>
        <security:authorize access="isAuthenticated()">
            <a href="/j_spring_security_logout"><spring:message code="logout"/> </a><br/> <spring:message code="welcome"/> <security:authentication
                property="principal.name"/>
        </security:authorize>
        <tiles:insertAttribute name="body"/>
    </div>
</body>
</html>
As you can see the main div uses mainDiv class. The css file which defines this class is inclued in the head. But not the exactly name of the css. It is determined from spring:theme tag.

OK. I think it is the time that you yourselves should take tour in the application. You can download source code from here. The needed jar files are not available in it. But the jar files are the same as older project. You can use Spring WebFlow sample jar files. there is a mysql database script available in [Project Root]/db/intermsg.sql. You can use it to restore the database in your mysql server. after running the application the admin user specification is:
username: administrator
password: 123456
The datasouce properties is available in [Project Root]/src/database.properties.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Wednesday, March 16, 2011

A Complete JQuery Sample

Hey...


So far we have learned JQuery-Core, JQuery-DOM, JQuery-CSS-JavaScript and JQuery-Events-Effects. Here I am going to present a sample to take some features we have learned.

Plane Rider

Plane Rider is a game which uses jquery. Some obstacles will be generated frequently and player should pass them. every 20 levels a new plane will be awarded. and in up level the obstacle generation rate will increase. Player can speed up or down by handling the available gears(from 1 to 5).

Game Logic

The game logic takes these major steps:
  1. Scene Creation: First of all the game scene should be created. It contains a game table and some other extra information such as saved plane, level, gear and so on.
  2. Plane Creation: In plane creation function, first the old position of the plane should vanish.
  3. Keydown Event Handling: Here left, top, right and down arrow keys, Esc and F1 keys should be handled on onkeydown.
  4. Play Game: This method call itself every specified time based on selected gear until ending of game.
    1. Create Obstacle: The obstacle should be created in every obstacle delay time(It is a setting variable. Its default value is 10)
    2. Redraw the plane: To have more accurate result of accident.
    3. Play Obstacles: This method iterates the obstacle array. First I should omit old position of obstacle then create obstacle in its new place. If the new place passes the game table ends it should vanish.
    4. Check Game: The obstacle array is iterated and if any cell has both obstacle and plane, the accident occurs. If there are some saved planes the obstacle should vanish and a new plane will assign the game. If there is no saved plane, it will be game over time.

JQuery Tricks

1. System Setting Extension
Any applications have its own settings like width, height, rows and so on. But the user who use our api can change them. On the other hands the consumer can change the system defaults or even extend it. In my sample, I create a system default object including width, height, rows and so on. I also add a new functions to jquery functions(the planeRider). So every jquery object of page elements have this function. This method take a setting object. This passed setting object has higher priority than system defaults. the code is available here.
    $.planeRider = {
        defaults:{
            width:600,
            height:200,
            rows:20,
            cols:60,
            delayObstacle:10,
            gears:[100,80,40,20,10],
            container:null
        }};

    $.fn.extend({
        planeRider: function(settings) {
            settings = $.extend({}, $.planeRider.defaults, settings);            settings.container = this;
            this.attr({align:'center'});
            startPlaneRider(settings);
        }
    });

2. Objective Java Script
In javascript any methods can be both function and class. If you want to create private methods for your class, you can create a function in the major function. If you want to have a public function you can create it by this object. Notice to this sample:
function testClass(){
  function privateFunction(){
  }
  this.publicFunction = function(){
  }
}
You can new an object instance of testClass and then call its publicFunction method like this.
var tc = new testClass();
tc.publicFunction();
In my sample I do all game functionalities in startPlaneRider class. It has a lot of inner functions. In planeRider method of jquery I just call this class.
$.fn.extend({
planeRider: function(settings) {
settings = $.extend({}, $.planeRider.defaults, settings);
settings.container = this;
this.attr({align:'center'});
startPlaneRider(settings);}
});
function startPlaneRider(settings) {
var gameCells = new Array();
var obstacleRep = new Array();
var playTime = settings.delayObstacle - 1;
var level = 1;
var obstacleCount = 0;
var currentRow = settings.rows / 2;
var lastCurrentRow = settings.rows / 2;
var currentGear = 0;
var savedPlane = 2;
var endGame = false;
var plane = $("<img></img>").attr({src:"images/Rocket-08-june.gif"}).css({position:"absolute"}).appendTo(settings.container);
createScene();
drawPlane();
$(document).keydown(function(event) {
...});
playGame();
function createScene() {
...}
...}

3. Crate HTML Elements And Setting Their Attributes
As we have learned, I create HTML elements dynamically and set their attributes using jquery API as easy as possible. Take a look to createScene sample:
function createScene() {
            var gameTable = $("<table></table");
            for (var i = 0; i < settings.rows; i++) {
                gameCells.push(new Array());
                var tr = $("<tr></tr>");
                for (var j = 0; j < settings.cols; j++) {
                    var td = $("<td></td>").css({'background-repeat':'no-repeat'}).attr({isPlane:false, isObstacle:false});                    td.appendTo(tr);                    gameCells[i].push(td);                }
                tr.appendTo(gameTable);            }
            gameTable.attr({'cellpadding':0, 'cellspacing':0}).css({width:settings.width, height:settings.height, 'border-width':'1px', 'border-style':'solid'});            gameTable.appendTo(settings.container);            $("<table></table>").css({width:settings.width}).append($("<tr></tr>").append($("<td></td>").append($("<div id='gearDiv'></div>").html("Gear:" + (currentGear + 1)))).append($("<td></td>").append($("<div id='levelDiv'></div>").html("Level:1"))).append($("<td></td>").append($("<table></table>").append($("<tr></tr>").append($("<td></td>").append($("<img></img>").attr({src:'images/jimbo.gif'}))).append($("<td></td>").append($("<span id='savedPlaneDiv'></span>").html("2")))))).append($("<td></td>").append($("<div id='helpDiv'></div>").html("Press F1 to help you...")))).appendTo(settings.container);}
All red lines are jquery API.

4. Position of an element
I set some extra attributes for any cells of the game table: isObstacle and isPlane. In the game scenario I will play these attributes and realize if a cell has obstacle or plain. I use a plane image on the cells which are plane cells. So I should find the position of the plane cells and move plane image to their top and left. JQuery has a very useful API for that. See this:
        function drawPlane() {
            clearPlane();
            for(var i = 13; i >=4; i--){
                gameCells[currentRow][i].attr({isPlane:true});
            }
            for(var i = 10; i >=4; i--){
                gameCells[currentRow - 1][i].attr({isPlane:true});
            }
            for(var i = 13; i >=4; i--){
                gameCells[currentRow + 1][i].attr({isPlane:true});
            }
            for(var i = 6; i >=4; i--){
                gameCells[currentRow + 2][i].attr({isPlane:true});
            }
            var pos = gameCells[currentRow - 1][0].offset();
            plane.css({top:pos.top, left:pos.left});

        }
I use the top left corner cell of the plane and find its position then move the plane image.

5. Animation and Effect
When Game Over take place a faded window including the "Game Over" text should be shown. It should the fade opacity should increase incrementally. JQuery has a very simple and useful API for that. Take a look this:
        function checkGame() {
            for (var i = 0; i < obstacleRep.length; i++) {
                if (gameCells[obstacleRep[i].row][obstacleRep[i].col].attr("isPlane").toString() == "true" && gameCells[obstacleRep[i].row][obstacleRep[i].col].attr("isObstacle").toString() == "true") {
                    if (savedPlane > 0) {
                        alert("accident...");
                        deleteObstacle(obstacleRep[i]);
                        i--;
                        savedPlane --;
                        $("#savedPlaneDiv").html(savedPlane);
                    } else {
                        endGame = true;
                        $("<div></div>").hide().append($("<div></div>").html("Game Over").

css({top:"50%", left:"50%", position:"absolute", padding:3, 'background-color':'#fff', border:'1px solid #ccc', color:'#f00'})).
css({position:"absolute", width:"100%", height:"100%", top:0, left:0, "background-color":"gray"}).
appendTo(settings.container).fadeTo("slow", 0.8);                        return false;
                    }
                }
            }
            return true;
        }
I do this just by fadeTo function. You can read this method and other similar methods specifications in my previous post.


I think its the time to download the sample and take tour in it yourselves. again I retell that all those jquery methods which I used in this sample and other extra jquery methods have been explained in my previous posts. Please refer to them to catch jquery concepts more.


By the way happy norooz to all persian ones...
Have nice days in your HOLIDAY...



all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Monday, March 14, 2011

Spring-WebFlow

Introduction

Traditionally, defining the user interface (UI) flow in a web application has been a less than intuitive process. Frameworks like Struts and Spring Web MVC force you to cut the UI flow into individual controllers and views. Struts, for instance, will map a request to an action. The action will then select a view and forward to it. Although this is a simple and functional system, it has a major disadvantage: the overall UI flow of the web application is not at all clear from looking at the action definitions in the struts-config.xml file. Flexibility also suffers since actions cannot easily be reused.

The Spring Web MVC framework offers a slightly higher level of functionality: form controllers that implement a predefined work flow. Two such controllers are provided out of the box: SimpleFormController and AbstractWizardFormController. However, these are still hard coded examples of a more general work flow concept.

This is where Spring Web Flow comes in, allowing you to represent the UI flow in (part of) a web application in a clear and simple way. As we will see, this has several advantages:

  • The UI flow in a web application is clearly visible by looking at the corresponding web flow definition (typically in an XML file).
  • Web Flows can be designed to be self contained. This allows you to see a part of your application as a module and reuse it in multiple situations.
  • Web Flows can define any reasonable UI flow in a web application, always using the same consistent technique. You're not forced into using specialized controllers for very particular situations.

For now it suffices to say that a Web Flow is composed of a set of states. A state is a point in the flow where something happens: for instance showing a view or executing an action. Each state has one or more transitions that are used to move to another state. A transition is triggered by an event. To give you an impression of what a Web Flow might look like, I peresent a sample.

Sample Project



Here I am presenting a simple usecase. The usecase is a simple CRUD based on  testflow entity. Here is state diagram
image 1

At the begining of the flow you see a list of testflow entity. You can view the detail in view state. Then you can edit it or back. The back is end of the flow. In Edit state you can save or delete or back to view state.
The class diagram is available here
image 2
WebFlow Configuration

Here is a complete simple SpringWebFlow configuration. This configuration uses SpringMVC as presentation. You also can use JSF, Struts, ...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:webflow="http://www.springframework.org/schema/webflow-config"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/webflow-config
           http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">

    <webflow:flow-executor id="flowExecutor">
        <webflow:flow-execution-listeners>
            <webflow:listener ref="securityFlowExecutionListener" />
        </webflow:flow-execution-listeners>
    </webflow:flow-executor>

    <webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
        <webflow:flow-location-pattern value="/**/*-config.xml"/>
    </webflow:flow-registry>
    <webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator" development="true" />
    <bean id="mvcViewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
        <property name="viewResolvers" ref="tilesViewResolver"/>
        <property name="useSpringBeanBinding" value="true" />
    </bean>
    <bean name="/user/flows.html" class="org.springframework.webflow.mvc.servlet.FlowController">
        <property name="flowExecutor" ref="flowExecutor"/>
        <property name="flowUrlHandler">
            <bean class="org.springframework.webflow.context.servlet.WebFlow1FlowUrlHandler"/>
        </property>
    </bean>

    <!-- Installs a listener to apply Spring Security authorities -->
    <bean id="securityFlowExecutionListener" class="org.springframework.webflow.security.SecurityFlowExecutionListener" />
</beans>
There are some points in this configuration. In "flow-registry" I configure every files with "/**/*-config.xml" is a webflow configuartion files which contaings stats, transition and so on. In "flow-builder-services" I use "mvcViewFactoryCreator" bean as view factory. I define a bean called "/user/flows.html" type of "org.springframework.webflow.mvc.servlet.FlowController". Here I mean the flow url is "/user/flows.html". The request parameter will select a specific flow.
When the Web Flow controller is invoked by the dispatcher servlet to handle a request, it examines the request parameters to determine what to do. The following request parameters are recognized:
NameDescription
_flowIdThe value of this parameter provides the id of a flow for which a new execution should be launched. Possible values in our sample application are search-flow and detail-flow.
_flowExecutionKeyThe unique id of an ongoing flow execution. The flow executor will use this to resume an ongoing flow execution.
_eventIdThe event that will be triggered in the current state of the flow. It is required when accessing an ongoing flow execution and not used when launching a new flow execution.
Using the values of the request parameters specified above, the flow controller implements the following logic:

  • When a request comes in, the "_flowExecutionKey" parameter is retrieved from the request.
    • When present, the flow controller will restore the ongoing flow execution and resume it.
    • If it is not present, the flow controller launches a new flow execution for the flow identified using the "_flowId" parameter. The new execution will be assigned a unique key.
  • For an existing flow execution, the value of the "_eventId" request parameter will be used to trigger a transition defined in the current state of the flow. If no event id is specified, the flow execution will just be refreshed.
  • The outcome of the steps above is a response instruction containing a model and a view to render. The flow execution key is available in the model using the name "flowExecutionKey". This key can be used by the view to reference back to the ongoing flow execution.

We now have enough information to add a link to our test flow in the view.jsp general tiles page. Since we want to launch a new flow, we only need to provide the "_flowId" request paramter in the request to the Web Flow controller. The following piece of HTML does exactly that:
<a href="<spring:url value="/user/flows.html?_flowId=testflow-config"/>">Webflow Sample</a>
testflow-config is exactly a flow configuration file name("[project root]/web/WEB-INF/pages/testflow/testflow-config.xml").

Web Flow Principles

With all the infrastructure in place, we are now ready to start looking at Web Flows and what they can do for you. Technically, a Web Flow is nothing more than an XML file representation of the UI flow of a web application. This XML format is defined in an XML schema. To properly indicate that an XML file contains a Web Flow definition, it should contain the following schema reference:
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

...
The Web Flow schema defines that a flow is composed of a set of states. Each state will have a unique id in the flow. The following state types are supported.

  • start-state - Each flow must have a single start state. This is a marker state defining the id of another state in the flow where flow execution will start.
  • action-state - A flow can have multiple action states, defining places in the Web Flow where actions take place. An action normally involves such things as processing user input, interacting with the business layer or preparing model data for a view.
  • view-state - View states define points in the flow where a view (page) will be shown. A Web Flow can have multiple view states.
  • decision-state - Decision states take routing decisions, selecting possible paths through a flow.
  • subflow-state - This state type launches another Web Flow as a subflow. It allows you to reuse a flow from inside another flow. Attribute mappers are used to exchange data between a flow and its subflows.
  • end-state - A state signaling the end of flow execution. Note that a Web Flow can have multiple end states, each representing another final situation (success, error, ...). An end state can optionally have an associated view that will be rendered when the end state is reached if there is no other view to render (e.g. in a parent flow).

As explained in the introduction, each state in a Web Flow (except for the start and end states) defines a number of transitions to move from one state to another. A transition is triggered by an event signaled inside a state. The way a state signals events depends on the state type. For a view state, the event is based on user input submitted to the controller using the "_eventId" request parameter. In case of an action state, the executed actions signal events. Subflow-states signal events based on the outcome of the subflow they spawned.

My sample of testflow-config.xml is available here:
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

    <view-state id="list" view="testflow.list" model="testflow">
        <on-render>
            <evaluate expression="testflowService.findAll()" result="requestScope.testflowList"/>
        </on-render>
        <transition on="add" to="edit">
            <evaluate expression="testflowService.createEntity()" result="flowScope.testflow"/>
        </transition>
        <transition on="view" to="view">
            <evaluate expression="testflowService.findById(requestParameters.selectedId)"
                      result="flowScope.testflow"></evaluate>
        </transition>
    </view-state>
    <view-state id="view" view="testflow.view" model="testflow">
        <transition on="back" to="finish"></transition>
        <transition on="edit" to="edit"></transition>
    </view-state>
    <view-state id="edit" view="testflow.edit" model="testflow">
        <transition on="back" to="view"></transition>
        <transition on="save" to="saving">
        </transition>
        <transition on="delete" to="deleting">
        </transition>
    </view-state>

    <decision-state id="saving">
        <on-entry>
            <evaluate expression="testflowService.saveSuccessMessage"
                      result="flashScope.saveSuccessMessage"></evaluate>
            <evaluate expression="testflowService.saveErrorMessage"
                      result="flashScope.saveErrorMessage"></evaluate>
        </on-entry>
        <if test="testflowService.saveOrUpdate(testflow)" then="view" else="edit"/>
    </decision-state>
    <decision-state id="deleting">
        <on-entry>
            <evaluate expression="testflowService.deleteSuccessMessage"
                      result="flashScope.deleteSuccessMessage"></evaluate>
            <evaluate expression="testflowService.deleteErrorMessage"
                      result="flashScope.deleteErrorMessage"></evaluate>
        </on-entry>
        <if test="testflowService.delete(testflow)" then="view" else="edit"/>
    </decision-state>
    <end-state id="finish"/>
</flow>
The flow diagram is described in image 1.

Views

Implementing views used in a Spring Web Flow based application is not that different from view implementation in any other Spring Web MVC application. The only point of interest is linking back to the flow controller and signaling an event. The sample application uses JSP 2.0 as view technology with embedded JSP EL expressions. The Spring 2 bind and form tag libraries are also used.
Let's start by looking at the "list" view, implemented in [Project Root]/web/WEB-INF/pages/testflow/testflow-listjsp. This page shows a list of testflow entity.
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>List Page</title></head>
<body>
<form:form commandName="testflow">
    <input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}"/>
    <input type="hidden" name="selectedId" id="selectedId"/>
    <table>
        <tr>
            <th>firstname</th>
            <th>lastname</th>
            <th></th>
        </tr>
        <c:forEach items="${testflowList}" var="testflow">
            <tr>
                <td>${testflow.firstname}</td>
                <td>${testflow.lastname}</td>
                <td><input type="submit" name="_eventId_view" value="view"
                           onclick="document.getElementById('selectedId').value = '${testflow.id}';"/></td>
            </tr>
        </c:forEach>
    </table>
    <input type="submit" name="_eventId_add" value="add"/>
</form:form>
</body>
</html>
First of all, notice that we do not specify an "action" on the form. This page is served by the flow controller so the Spring Web MVC form tag library will automatically post the form back to the flow controller. In other words, the form submission will be handled by our Web Flow controller. The next thing to notice is the two special inputs that are contained in the form:

  • The hidden field "_flowExecutionKey" is filled with the flow execution key of the current flow execution. As explained above, this key is exposed to the view using the name "flowExecutionKey".
  • The "_eventId" is encoded in the name of a button field. Alternatively we could have used a hidden field with as name "_eventId" and as value "search".

When the form is submitted by add button, the "add" event will be signaled in the current state of the flow. The current state is the "list" view state, so in response to the "add" event, the flow will transition to the "edit" view state and render the "edit" view but befor the transition "testflowService.createEntity()" will be called and set the result to "flowScope.testflow".

The "edit" view implemented in [Project Root]/web/WEB-INF/pages/testflow/testflow-edit.jsp and the "view" view implemented in [Project Root]/web/WEB-INF/pages/testflow/testflow-view.jsp are very similar.

Scopes
There are several scopes defined by Spring Web Flow through the request context and flow configuration file. The union of all data available in the different scopes will be exposed to a view when it is rendered. Spring Web Flow defines the following scopes:

  • request scope - Local to a single request into the Web Flow system.
  • flash scope - Scoped at the level of a user event signaled in an ongoing flow execution. Survives any refreshes of that flow execution.
  • flow scope - Persists for the life of a flow session. The states in a flow can share information using flow scope. A parent flow has a different flow session than a subflow.
  • conversation scope - Available to all flow sessions in a conversation.
As you can see I used "requestScope", "flashScope", "flowScope" in "testflow-conf.xml" configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

    <view-state id="list" view="testflow.list" model="testflow">
        <on-render>
            <evaluate expression="testflowService.findAll()" result="requestScope.testflowList"/>
        </on-render>
        <transition on="add" to="edit">
            <evaluate expression="testflowService.createEntity()" result="flowScope.testflow"/>
        </transition>
        <transition on="view" to="view">
            <evaluate expression="testflowService.findById(requestParameters.selectedId)"
                      result="flowScope.testflow"></evaluate>
        </transition>
    </view-state>
    <view-state id="view" view="testflow.view" model="testflow">
        <transition on="back" to="finish"></transition>
        <transition on="edit" to="edit"></transition>
    </view-state>
    <view-state id="edit" view="testflow.edit" model="testflow">
        <transition on="back" to="view"></transition>
        <transition on="save" to="saving">
        </transition>
        <transition on="delete" to="deleting">
        </transition>
    </view-state>

    <decision-state id="saving">
        <on-entry>
            <evaluate expression="testflowService.saveSuccessMessage"
                      result="flashScope.saveSuccessMessage"></evaluate>
            <evaluate expression="testflowService.saveErrorMessage"
                      result="flashScope.saveErrorMessage"></evaluate>
        </on-entry>
        <if test="testflowService.saveOrUpdate(testflow)" then="view" else="edit"/>
    </decision-state>
    <decision-state id="deleting">
        <on-entry>
            <evaluate expression="testflowService.deleteSuccessMessage"
                      result="flashScope.deleteSuccessMessage"></evaluate>
            <evaluate expression="testflowService.deleteErrorMessage"
                      result="flashScope.deleteErrorMessage"></evaluate>
        </on-entry>
        <if test="testflowService.delete(testflow)" then="view" else="edit"/>
    </decision-state>
    <end-state id="finish"/>
</flow>

I think another post is needed to take Subflows and Attribute Mappers sample. But now it is the time to download the application and try it yourselves. After deploying the start page URL will be: "http://localhost:8080/user/flows.html?_flowId=testflow-config"
The mysql schema script is available in "[Project Root]/db/springwebflow.sql" you can restore it to your mysqlserver. The datasource property is available here: "[Project Root]/src/database.properties". When you run the application you should first login. The Administrator specifications is:
Username: administrator
Password: 123456

Enjoy yourselves with Spring-WebFlow



all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Saturday, March 12, 2011

JQuery-Events-Effects

Hi everybody...

We have been working on JQuery-Core, JQuery-DOM and JQuery-CSS-JavaScript yet. Here I am going to explain JQuery-Events and JQuery-Effects.
Ok let's go...

5. Events

5.1 bind(String,Object,Function)
bind(String type, Object data, Function fn) returns jQuery

Binds a handler to a particular event (like click) for each matched element. The event handler
is passed an event object that you can use to prevent default behaviour. To stop both default
action and event bubbling, your handler has to return false.
In most cases, you can define your event handlers as anonymous functions (see first
example). In cases where that is not possible, you can pass additional data as the second
paramter (and the handler function as the third), see  second example.

Example:
$("p").bind("click", function(){
 alert( $(this).text() );
});
HTML:
<p>Hello</p>
Result:
alert("Hello")

Example:
Pass some additional data to the event handler.
function handler(event) {
 alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
Result:
alert("bar")
 
Example:
Cancel a default action and prevent it from bubbling by returning false from your function.
$("form").bind("submit", function() { return false; })

Example:
Cancel only the default action by using the preventDefault method.
$("form").bind("submit", function(event){
 event.preventDefault();
});

Example:
Stop only an event from bubbling by using the stopPropagation method.
$("form").bind("submit", function(event){
 event.stopPropagation();
});

5.2  one(String,Object,Function)
one(String type, Object data, Function fn) returns jQuery

Binds a handler to a particular event (like click) for each matched element. The handler is
executed only once for each element. Otherwise, the same rules as described in bind()
apply.
The event handler is passed an event object that you can use to prevent default behaviour.
To stop both default action and event bubbling, your handler has to return false.
In most cases, you can define your event handlers as anonymous functions (see first
example). In cases where that is not possible, you can pass additional data as the second
paramter (and the handler function as the third), see  second example.

Example:
$("p").one("click", function(){
 alert( $(this).text() );
});
HTML:
<p>Hello</p>
Result:
alert("Hello")

5.3 unbind(String,Function)
unbind(String type, Function fn) returns jQuery

The opposite of bind, removes a bound event from each of the matched elements.
Without any arguments, all bound events are removed.
If the type is provided, all bound events of that type are removed.
If the function that was passed to bind is provided as the second argument, only that specific
event handler is removed.

Example:
$("p").unbind()
HTML:
<p onclick="alert('Hello');">Hello</p>
Result:
[ <p>Hello</p> ]

Example:
$("p").unbind( "click" )
HTML:
<p onclick="alert('Hello');">Hello</p>
Result:
[ <p>Hello</p> ]

Example:
$("p").unbind( "click", function() { alert("Hello"); } )
HTML:
<p onclick="alert('Hello');">Hello</p>
Result:
[ <p>Hello</p> ]

5.4 trigger(String)
trigger(String type) returns jQuery

Trigger a type of event on every matched element.

Example:
$("p").trigger("click")
HTML:
<p click="alert('hello')">Hello</p>
Result:
alert('hello')

5.5. toggle(Function,Function)
toggle(Function even, Function odd) returns jQuery

Toggle between two function calls every other click. Whenever a matched element is clicked,
the first specified function  is fired, when clicked again, the second is fired. All subsequent
clicks continue to rotate through the two functions.
Use unbind("click") to remove.

Example:
$("p").toggle(function(){
 $(this).addClass("selected");
},function(){
 $(this).removeClass("selected");
});

5.6 hover(Function,Function)
hover(Function over, Function out) returns jQuery

A method for simulating hovering (moving the mouse on, and off, an object). This is a custom
method which provides an 'in' to a  frequent task.
Whenever the mouse cursor is moved over a matched  element, the first specified function is
fired. Whenever the mouse  moves off of the element, the second specified function fires.
Additionally, checks are in place to see if the mouse is still within  the specified element itself
(for example, an image inside of a div),  and if it is, it will continue to 'hover', and not move
out  (a common error in using a mouseout event handler).

Example:
$("p").hover(function(){
 $(this).addClass("over");
},function(){
 $(this).addClass("out");
});

5.7 ready(Function)
ready(Function fn) returns jQuery

Bind a function to be executed whenever the DOM is ready to be traversed and manipulated.
This is probably the most important  function included in the event module, as it can greatly
improve the response times of your web applications.
In a nutshell, this is a solid replacement for using window.onload,  and attaching a function to
that. By using this method, your bound Function  will be called the instant the DOM is ready
to be read and manipulated,  which is exactly what 99.99% of all Javascript code needs to
run.
There is one argument passed to the ready event handler: A reference to the jQuery function.
You can name that argument whatever you like, and can therefore stick with the $ alias
without risc of naming collisions.
Please ensure you have no code in your <body> onload event handler,  otherwise
$(document).ready() may not fire.
You can have as many $(document).ready events on your page as you like. The functions
are then executed in the order they were added.

Example:
$(document).ready(function(){ Your code here... });

Example:
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery
code using the $ alias, without relying on the global alias.
jQuery(function($) {
 // Your code using failsafe $ alias here...
});

5.8 scroll(Function)
scroll(Function fn) returns jQuery

Bind a function to the scroll event of each matched element.

Example:
$("p").scroll( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onscroll="alert('Hello');">Hello</p>

5.9 submit(Function)
submit(Function fn) returns jQuery

Bind a function to the submit event of each matched element.

Example:
Prevents the form submission when the input has no value entered.
$("#myform").submit( function() {
 return $("input", this).val().length > 0;
} );
HTML:
<form id="myform"><input /></form>

5.10 submit()
submit() returns jQuery

Trigger the submit event of each matched element. This causes all of the functions that have
been bound to thet submit event to be executed.
Note: This does not execute the submit method of the form element! If you need to submit
the form via code, you have to use the DOM method, eg. $("form")[0].submit();

Example:
Triggers all submit events registered for forms, but does not submit the form
$("form").submit();

5.11 focus(Function)
focus(Function fn) returns jQuery

Bind a function to the focus event of each matched element.

Example:
$("p").focus( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onfocus="alert('Hello');">Hello</p>

5.12 focus()
focus() returns jQuery

Trigger the focus event of each matched element. This causes all of the functions that have
been bound to thet focus event to be executed.
Note: This does not execute the focus method of the underlying elements! If you need to
focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();

Example:
$("p").focus();
HTML:
<p onfocus="alert('Hello');">Hello</p>
Result:
alert('Hello');

5.13 keydown(Function)
keydown(Function fn) returns jQuery

Bind a function to the keydown event of each matched element.

Example:
$("p").keydown( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onkeydown="alert('Hello');">Hello</p>

5.14 dblclick(Function)
dblclick(Function fn) returns jQuery

Bind a function to the dblclick event of each matched element.

Example:
$("p").dblclick( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p ondblclick="alert('Hello');">Hello</p>

5.15 keypress(Function)
keypress(Function fn) returns jQuery

Bind a function to the keypress event of each matched element.

Example:
$("p").keypress( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onkeypress="alert('Hello');">Hello</p>

5.16 error(Function)
error(Function fn) returns jQuery

Bind a function to the error event of each matched element.

Example:
$("p").error( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onerror="alert('Hello');">Hello</p>

5.17 blur(Function)
blur(Function fn) returns jQuery

Bind a function to the blur event of each matched element.

Example:
$("p").blur( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onblur="alert('Hello');">Hello</p>

5.18 blur()
blur() returns jQuery

Trigger the blur event of each matched element. This causes all of the functions that have
been bound to thet blur event to be executed.
Note: This does not execute the blur method of the underlying elements! If you need to blur
an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();

Example:
$("p").blur();
HTML:
<p onblur="alert('Hello');">Hello</p>
Result:
alert('Hello');

5.19 load(Function)
load(Function fn) returns jQuery

Bind a function to the load event of each matched element.

Example:
$("p").load( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onload="alert('Hello');">Hello</p>

5.20 select(Function)
select(Function fn) returns jQuery
Bind a function to the select event of each matched element.

Example:
$("p").select( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onselect="alert('Hello');">Hello</p>

5.21 select()
select() returns jQuery

Trigger the select event of each matched element. This causes all of the functions that have
been bound to thet select event to be executed.

Example:
$("p").select();
HTML:
<p onselect="alert('Hello');">Hello</p>
Result:
alert('Hello');

5.22 mouseup(Function)
mouseup(Function fn) returns jQuery

Bind a function to the mouseup event of each matched element.

Example:
$("p").mouseup( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onmouseup="alert('Hello');">Hello</p>

5.23 unload(Function)
unload(Function fn) returns jQuery

Bind a function to the unload event of each matched element.

Example:
$("p").unload( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onunload="alert('Hello');">Hello</p>

5.24 change(Function)
change(Function fn) returns jQuery

Bind a function to the change event of each matched element.

Example:
$("p").change( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onchange="alert('Hello');">Hello</p>

5.25 mouseout(Function)
mouseout(Function fn) returns jQuery

Bind a function to the mouseout event of each matched element.

Example:
$("p").mouseout( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onmouseout="alert('Hello');">Hello</p>

5.26 keyup(Function)
keyup(Function fn) returns jQuery

Bind a function to the keyup event of each matched element.

Example:
$("p").keyup( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onkeyup="alert('Hello');">Hello</p>

5.27 click(Function)
click(Function fn) returns jQuery

Bind a function to the click event of each matched element.

Example:
$("p").click( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onclick="alert('Hello');">Hello</p>

5.28 click()
click() returns jQuery

Trigger the click event of each matched element. This causes all of the functions that have
been bound to thet click event to be executed.

Example:
$("p").click();
HTML:
<p onclick="alert('Hello');">Hello</p>
Result:
alert('Hello');

5.29 resize(Function)
resize(Function fn) returns jQuery

Bind a function to the resize event of each matched element.

Example:
$("p").resize( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onresize="alert('Hello');">Hello</p>

5.30 mousemove(Function)
mousemove(Function fn) returns jQuery

Bind a function to the mousemove event of each matched element.

Example:
$("p").mousemove( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onmousemove="alert('Hello');">Hello</p>

5.31 mousedown(Function)
mousedown(Function fn) returns jQuery

Bind a function to the mousedown event of each matched element.

Example:
$("p").mousedown( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onmousedown="alert('Hello');">Hello</p>

5.32 mouseover(Function)
mouseover(Function fn) returns jQuery

Bind a function to the mouseover event of each matched element.

Example:
$("p").mouseover( function() { alert("Hello"); } );
HTML:
<p>Hello</p>
Result:
<p onmouseover="alert('Hello');">Hello</p>

6. Effects

6.1 show()
show() returns jQuery

Displays each of the set of matched elements if they are hidden.

Example:
$("p").show()
HTML:
<p style="display: none">Hello</p>
Result:
[ <p style="display: block">Hello</p> ]

6.2 show(String|Number,Function)
show(String|Number speed, Function callback) returns jQuery

Show all matched elements using a graceful animation and firing an optional callback after
completion.
The height, width, and opacity of each of the matched elements  are changed dynamically
according to the specified speed.

Example:
$("p").show("slow");

Example:
$("p").show("slow",function(){
 alert("Animation Done.");
});

6.3 hide()
hide() returns jQuery

Hides each of the set of matched elements if they are shown.

Example:
$("p").hide()
HTML:
<p>Hello</p>
Result:
[ <p style="display: none">Hello</p> ]

6.4 hide(String|Number,Function)
hide(String|Number speed, Function callback) returns jQuery

Hide all matched elements using a graceful animation and firing an optional callback after
completion.
The height, width, and opacity of each of the matched elements  are changed dynamically
according to the specified speed.

Example:
$("p").hide("slow");

Example:
$("p").hide("slow",function(){
 alert("Animation Done.");
});

6.5 toggle()
toggle() returns jQuery

Toggles each of the set of matched elements. If they are shown, toggle makes them hidden.
If they are hidden, toggle makes them shown.

Example:
$("p").toggle()
HTML:
<p>Hello</p><p style="display: none">Hello Again</p>
Result:
<p style="display: none">Hello</p>, <p style="display: block">Hello Again</p>

6.6 slideDown(String|Number,Function)
slideDown(String|Number speed, Function callback) returns jQuery

Reveal all matched elements by adjusting their height and firing an optional callback after
completion.
Only the height is adjusted for this animation, causing all matched elements to be revealed in
a "sliding" manner.

Example:
$("p").slideDown("slow");

Example:
$("p").slideDown("slow",function(){
 alert("Animation Done.");
});

6.7 slideUp(String|Number,Function)
slideUp(String|Number speed, Function callback) returns jQuery

Hide all matched elements by adjusting their height and firing an optional callback after
completion.
Only the height is adjusted for this animation, causing all matched elements to be hidden in a
"sliding" manner.

Example:
$("p").slideUp("slow");

Example:
$("p").slideUp("slow",function(){
 alert("Animation Done.");
});

6.8 slideToggle(String|Number,Function)
slideToggle(String|Number speed, Function callback) returns jQuery

Toggle the visibility of all matched elements by adjusting their height and firing an optional
callback after completion.
Only the height is adjusted for this animation, causing all matched elements to be hidden in a
"sliding" manner.

Example:
$("p").slideToggle("slow");

Example:
$("p").slideToggle("slow",function(){
 alert("Animation Done.");
});

6.9 fadeIn(String|Number,Function)
fadeIn(String|Number speed, Function callback) returns jQuery

Fade in all matched elements by adjusting their opacity and firing an optional callback after
completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements
should already have some form of height and width associated with them.

Example:
$("p").fadeIn("slow");

Example:
$("p").fadeIn("slow",function(){
 alert("Animation Done.");
});

6.10 fadeOut(String|Number,Function)
fadeOut(String|Number speed, Function callback) returns jQuery

Fade out all matched elements by adjusting their opacity and firing an optional callback after
completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements
should already have some form of height and width associated with them.

Example:
$("p").fadeOut("slow");

Example:
$("p").fadeOut("slow",function(){
 alert("Animation Done.");
});

6.11 fadeTo(String|Number,Number,Function)
fadeTo(String|Number speed, Number opacity, Function callback) returns jQuery

Fade the opacity of all matched elements to a specified opacity and firing an optional
callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements
should already have some form of height and width associated with them.

Example:
$("p").fadeTo("slow", 0.5);

Example:
$("p").fadeTo("slow", 0.5, function(){
 alert("Animation Done.");
});

6.12 animate(Hash,String|Number,String,Function)
animate(Hash params, String|Number speed, String easing, Function callback) returns jQuery

A function for making your own, custom, animations. The key aspect of this function is the
object of style properties that will be animated, and to what end. Each key within the object
represents a style property that will also be animated (for example: "height", "top", or
"opacity").
The value associated with the key represents to what end the property will be animated. If a
number is provided as the value, then the style property will be transitioned from its current
state to that new number. Oterwise if the string "hide", "show", or "toggle" is provided, a
default animation will be constructed for that property.

Example:
$("p").animate({
 height: 'toggle', opacity: 'toggle'
}, "slow");

Example:
$("p").animate({
 left: 50, opacity: 'show'
}, 500);

Example:
An example of using an 'easing' function to provide a different style of animation. This will
only work if you have a plugin that provides this easing function (Only 'linear' is provided by
default, with jQuery).
$("p").animate({
 opacity: 'show'
}, "slow", "easein");

Ok. I think if you pass my JQuery training posts, you will be able to write your own needed jquery scripts. To improve more our jquery skill, I think it is good to do a sample using jquery. In my next JQuery post I will describe my new JQuery based game; Car Driving Game.



all rights reserved by Mostafa Rastgar and Programmer Assistant weblog