Thursday 18 July 2013

SOAP

SOAP


SOAP is a simple and open standard XML-based protocol for exchanging information between computers.

What is SOAP?

SOAP is an XML-based protocol for exchanging information between computers.
SOAP is XML. That is, SOAP is an application of the XML specification.
All statements are TRUE for SOAP
  • SOAP is acronym for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is designed to communicate via Internet
  • SOAP can extend HTTP for XML messaging
  • SOAP provides data transport for Web services
  • SOAP can exchange complete documents or call a remote procedure
  • SOAP can be used for broadcasting a message
  • SOAP is platform and language independent
  • SOAP is the XML way of defining what information gets sent and how
Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the initial focus of SOAP is remote procedure calls transported via HTTP.
SOAP enables client applications to easily connect to remote services and invoke remote methods.
Other frameworks, including CORBA, DCOM, and Java RMI, provide similar functionality to SOAP, but SOAP messages are written entirely in XML and are therefore uniquely platform- and language-independent.

SOAP - Recommended Knowledge

It is recommended that before you proceed further you should be familiar with XML and XML namespace.

SOAP Message Structure


A SOAP message is an ordinary XML document containing the following elements.
  • Envelope: ( Mandatory )
    Defines the start and the end of the message.
  • Header: ( Optional )
    Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end point.
  • Body: ( Mandatory )
    Contains the XML data comprising the message being sent.
  • Fault: ( Optional )
    An optional Fault element that provides information about errors that occurred while processing the message
All these elements are declared in the default namespace for the SOAP envelope:
and the default namespace for SOAP encoding and data types is:
NOTE: All these specificiations are subject to change. So keep updating yourself with the latest specifications available W3 website.

A SOAP Message Structure

<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Header>
  ...
  ...
</SOAP-ENV:Header>
<SOAP-ENV:Body>

  ...
  ...
  <SOAP-ENV:Fault>
    ...
    ...
  </SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP_ENV:Envelope>



SOAP Envelope Element


The SOAP envelope indicates the start and the end of the message so that the receiver knows when an entire message has been received. The SOAP envelope solves the problem of knowing when you're done receiving a message and are ready to process it. The SOAP envelope is therefore basic ally a packaging mechanism
SOAP Envelope element can be explained as:
  • Every SOAP message has a root Envelope element.
  • Envelope element is mandatory part of SOAP Message.
  • Every Envelope element must contain exactly one Body element.
  • If an Envelope contains a Header element, it must contain no more than one, and it must appear as the first child of the Envelope, beforethe Body.
  • The envelope changes when SOAP versions change.
  • The SOAP envelope is specified using the ENV namespace prefix and the Envelopeelement.
  • The optional SOAP encoding is also specified using a namespace name and the optionalencodingStyle element, which could also point to an encoding style other than the SOAP one.
  • A v1.1-compliant SOAP processor will generate a fault when receiving a message containing the v1.2 envelope namespace.
  • A v1.2- compliant SOAP processor generates a VersionMismatch fault if it receives a message that does not include the v1.2 envelope namespace.
Example for v1.2 is given below
<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"

SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
  ...
  Message information goes here
  ...
</SOAP-ENV:Envelope>
Following example illustrates the use of a SOAP message within an HTTP POST operation, which sends the message to the server. It shows the namespaces for the envelope schema definition and for the schema definition of the encoding rules. The OrderEntry reference in the HTTP header is the name of the program to be invoked at the only4programmers.blogspot.com Web site.
POST /OrderEntry HTTP/1.1
Host: www.only4programmers.blogspot.com.com
Content-Type: application/soap; charset="utf-8"
Content-Length: nnnn
<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
  ...
  Message information goes here
  ...
</SOAP-ENV:Envelope>
NOTE: The HTTP binding specifies the location of the service.



SOAP Header Element

The optional Header element offers a flexible framework for specifying additional application-level requirements. For example, the Header element can be used to specify a digital signature for password-protected services; likewise, it can be used to specify an account number for pay-per-use SOAP services.
SOAP Header element can be explained as:
  • Header elements are optional part of SOAP messages.
  • Header elements can occur multiple times.
  • Headers are intended to add new features and functionality
  • The SOAP header contains header entries defined in a namespace.
  • The header is encoded as the first immediate child element of the SOAP envelope.
  • When more than one header is defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks.
SOAP Header element can have following two attributes
  • Actor attribute:
    The SOAP protocol defines a message path as a list of SOAP service nodes. Each of these intermediate nodes can perform some processing and then forward the message to the next node in the chain. By setting the Actor attribute, the client can specify the recipient of the SOAP header.
  • MustUnderstand attribute
    Indicates whether a Header element is optional or mandatory. If set to true ie. 1 the recipient must understand and process the Header attribute according to its defined semantics, or return a fault.
Following example shows how to use a Header in the SOAP message.
<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Header>
<t:Transaction
xmlns:t="http://www.only4programmers.blogspot.com/transaction/"
SOAP-ENV:mustUnderstand="true">5</t:Transaction>
</SOAP-ENV:Header>
...
...
</SOAP-ENV:Envelope>



SOAP Body Element

The SOAP body is a mandatory element which contains the application-defined XML data being exchanged in the SOAP message. The body must be contained within the envelope and must follow any headers that might be defined for the message. The body is defined as a child element of the envelope, and the semantics for the body are defined in the associated SOAP schema.
The body contains mandatory information intended for the ultimate receiver of the message. For example:
<?xml version="1.0"?>

<SOAP-ENV:Envelope
........
<SOAP-ENV:Body>
   <m:GetQuotation xmlns:m="http://www.tp.com/Quotation">
      <m:Item>Computers</m:Item>
   </m:GetQuotation>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The example above requests the quotation of computer sets. Note that the m:GetQuotation and the Item elements above are application-specific elements. They are not a part of the SOAP standard.
Here is the response of above query:
<?xml version="1.0"?>

<SOAP-ENV:Envelope
........
<SOAP-ENV:Body>
   <m:GetQuotationResponse xmlns:m="http://www.tp.com/Quotation">
      <m:Quotation>This is Qutation</m:Quotation>
   </m:GetQuotationResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Normally, the application also defines a schema to contain semantics associated with the request and response elements.
The Quotation service might be implemented using an EJB running in an application server; if so, the SOAP processor would be responsible for mapping the body information as parameters into and out of the EJB implementation of the GetQuotationResponse service. The SOAP processor could also be mapping the body information to a .NET object, a CORBA object, a COBOL program, and so on.




SOAP Fault Element

When an error occurs during processing, the response to a SOAP message is a SOAP fault element in the body of the message, and the fault is returned to the sender of the SOAP message.
The SOAP fault mechanism returns specific information about the error, including a predefined code, a description, the address of the SOAP processor that generated
  • A SOAP Message can carry only one fault block
  • Fault element is an optional part of SOAP Message
  • For the HTTP binding, a successful response is linked to the 200 to 299 range of status codes;
  • SOAP fault is linked to the 500 to 599 range of status codes.
The SOAP Fault element has the following sub elements:
Sub ElementDescription
<faultCode>A text code used to indicate a class of errors. See the next Table for a listing of predefined fault codes.
<faultString>A text message explaning the error
<faultActor>A text string indicating who caused the fault. This is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needs to know which node caused the error. A node that does not act as the ultimate destination must include a faultActor element.
<detail>An element used to carry application-specific error messages. The detail element can contain child elements, called detail entries.

SOAP Fault Codes

The faultCode values defined below must be used in the faultcode element when describing faults
ErrorDescription
SOAP-ENV:VersionMismatchFound an invalid namespace for the SOAP Envelope element
SOAP-ENV:MustUnderstandAn immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood
SOAP-ENV:ClientThe message was incorrectly formed or contained incorrect information
SOAP-ENV:ServerThere was a problem with the server so the message could not proceed

SOAP Fault Example

The following code is a sample Fault. The client has requested a method named ValidateCreditCard , but the service does not support such a method. This represents a client request error, and the server returns the following SOAP response:
<?xml version='1.0' encoding='UTF-8'?>

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/1999/XMLSchema">
   <SOAP-ENV:Body>
     <SOAP-ENV:Fault>
     <faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
     <faultstring xsi:type="xsd:string">
          Failed to locate method (ValidateCreditCard) in class
          (examplesCreditCard) at /usr/local/ActivePerl-5.6/lib/
            site_perl/5.6.0/SOAP/Lite.pm line 1555.
        </faultstring>

      </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>



SOAP Encoding

SOAP includes a built-in set of rules for encoding data types.This enables the SOAP message to indicate specific data types, such as integers, floats, doubles, or arrays.
  • SOAP data types are divided into two broad categories: scalar types and compound types.
  • Scalar types contain exactly one value, such as a last name, price, or product description.
  • Compound types contain multiple values, such as a purchase order or a list of stock quotes.
  • Compound types are further subdivided into arrays and structs.
  • The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute.
  • To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/
  • To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/12/soap-encoding
  • Latest SOAP specification adopts all the built-in types defined by XML Schema. Still SOAP maintains its own convention for defining constructs not standardized by XML Schema, such as arrays and references.

Scalar Types

For scalar types, SOAP adopts all the built-in simple types specified by the XML Schema specification. This includes strings, floats, doubles, and integers.
Following table lists the main simple types, excerpted from the XML Schema Part 0: Primer
http://www.w3.org/TR/2000/WD-xmlschema-0-20000407/
Simple Types Built-In to XML Schema
Simple TypeExample(s)
stringConfirm this is electric
booleantrue, false, 1, 0
float-INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN
double-INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN
decimal-1.23, 0, 123.4, 1000.00
binary100010
integer-126789, -1, 0, 1, 126789
nonPositiveInteger-126789, -1, 0
negativeInteger-126789, -1
long-1, 12678967543233
int-1, 126789675
short-1, 12678
byte-1, 126
nonNegativeInteger0, 1, 126789
unsignedLong0, 12678967543233
unsignedInt0, 1267896754
unsignedShort0, 12678
unsignedByte0, 126
positiveInteger1, 126789
date1999-05-31, ---05
time13:20:00.000, 13:20:00.000-05:00
For example, here is a SOAP response with a double data type:
<?xml version='1.0' encoding='UTF-8'?*gt;
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
    <ns1:getPriceResponse
    xmlns:ns1="urn:examples:priceservice"
    SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
    <return xsi:type="xsd:double">54.99</return>
    </ns1:getPriceResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Compound Types

SOAP arrays have a very specific set of rules, which require that you specify both the element type and array size. SOAP also supports multidimensional arrays, but not all SOAP implementations support multidimensional functionality.
To create an array, you must specify it as an xsi:type of Array. The array must also include an arrayType attribute. This attribute is required to specify the data type for the contained elements and the dimension(s) of the array.
For example, the following attribute specifies an array of 10 double values:
arrayType="xsd:double[10]"
In contrast, the following attribute specifies a two-dimensional array of strings:
arrayType="xsd:string[5,5]"
Here is a sample SOAP response with an array of double values:
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
    <ns1:getPriceListResponse
    xmlns:ns1="urn:examples:pricelistservice"
    SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
    <return
    xmlns:ns2="http://www.w3.org/2001/09/soap-encoding"
    xsi:type="ns2:Array" ns2:arrayType="xsd:double[2]">
    <item xsi:type="xsd:double">54.99</item>
    <item xsi:type="xsd:double">19.99</item>
    </return>
    </ns1:getPriceListResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Structs contain multiple values, but each element is specified with a unique accessor element. For example, consider an item within a product catalog. In this case, the struct might contain a product SKU, product name, description, and price. Here is how such a struct would be represented in a SOAP message:
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
      <ns1:getProductResponse
   xmlns:ns1="urn:examples:productservice"
   SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
   <return xmlns:ns2="urn:examples" xsi:type="ns2:product">
   <name xsi:type="xsd:string">Red Hat Linux</name>
   <price xsi:type="xsd:double">54.99</price>
   <description xsi:type="xsd:string">
         Red Hat Linux Operating System
   </description>
   <SKU xsi:type="xsd:string">A358185</SKU>
   </return>
   </ns1:getProductResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
NOTE: Please you take care of proper indentation while you write your SOAP code.
Each element in a struct is specified with a unique accessor name. For example, the message above includes four accessor elements: name , price , description , and SKU. Each element can have its own data type; for example, name is specified as a string , whereas price is specified as a double.



SOAP Transport

  • SOAP is not tied to any one transport protocol.
  • SOAP can be transported via SMTP, FTP, IBM's MQSeries, or Microsoft Message Queuing (MSMQ).
  • SOAP specification includes details on HTTP only.
  • HTTP remains the most popular SOAP transport protocol.

SOAP via HTTP

Quite logically, SOAP requests are sent via an HTTP request and SOAP responses are returned within the content of the HTTP response. While SOAP requests can be sent via an HTTP GET, the specification includes details on HTTP POST only.
Additionally, both HTTP requests and responses are required to set their content type to text/xml.
The SOAP specification mandates that the client must provide a SOAPAction header, but the actual value of the SOAPAction header is dependent on the SOAP server implementation.
For example, to access the AltaVista BabelFish Translation service, hosted by XMethods, you must specify the following as a SOAPAction header.
urn:xmethodsBabelFish#BabelFish
Even if the server does not require a full SOAPAction header, the client must specify an empty string (""), or a null value. For example:
SOAPAction: ""
SOAPAction:
Here is a sample request sent via HTTP to the XMethods Babelfish Translation service:
POST /perl/soaplite.cgi HTTP/1.0
Host: services.xmethods.com
Content-Type: text/xml; charset=utf-8
Content-Length: 538
SOAPAction: "urn:xmethodsBabelFish#BabelFish"

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<ns1:BabelFish
xmlns:ns1="urn:xmethodsBabelFish"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<translationmode xsi:type="xsd:string">en_fr</translationmode>
<sourcedata xsi:type="xsd:string">Hello, world!</sourcedata>
</ns1:BabelFish>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Note the content type and the SOAPAction header. Also note that the BabelFish method requires two String parameters. The translation mode en_fr will translate from English to French.
Here is the response from XMethods:
HTTP/1.1 200 OK
Date: Sat, 09 Jun 2001 15:01:55 GMT
Server: Apache/1.3.14 (Unix) tomcat/1.0 PHP/4.0.1pl2
SOAPServer: SOAP::Lite/Perl/0.50
Cache-Control: s-maxage=60, proxy-revalidate
Content-Length: 539
Content-Type: text/xml

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<namesp1:BabelFishResponse xmlns:namesp1="urn:xmethodsBabelFish">
<return xsi:type="xsd:string">Bonjour, monde!</return>
</namesp1:BabelFishResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

SOAP responses delivered via HTTP are required to follow the same HTTP status codes. For example, a status code of 200 OK indicates a successful response. A status code of 500 Internal Server Error indicates that there is a server error and that the SOAP response includes a Fault element.



SOAP Standards

SOAP 1.1 was originally submitted to the W3C in May 2000. Official submitters included large companies, such as Microsoft, IBM, and Ariba, and smaller companies, such as UserLand Software and DevelopMentor.
In July 2001, the XML Protocol Working Group released a "working draft" of SOAP 1.2. Within the W3C, this document is officially a work in progress, meaning that the document is likely to be updated many times before it is finalized.
SOAP Version 1.1 is available online at
http://www.w3.org/TR/SOAP/
The working draft of SOAP Version 1.2 is available at
http://www.w3.org/TR/soap12/
Note that the W3C also hosts a submission for "SOAP Messages with Attachments", which separates from the core SOAP specification. This specification enables SOAP messages to include binary attachments, such as images and sound files. For full details, see the W3C Note at
http://www.w3.org/TR/SOAP-attachments.


Saturday 22 June 2013

JQuery


jQuery Tutorial


jQuery Tutorial


jQuery is a fast and concise JavaScript library created by John Resig in 2006.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for Rapid Web Development.
This tutorial gives a a very good understanding on basics of jQuery version 1.3.2.

   jQuery - Overview

What is jQuery ?

jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto:Write less, do more.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery:
  • DOM manipulation: The jQuery made it easy to select DOM elements, traverse them and modifying their content by using cross-browser open source selector engine calledSizzle.
  • Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
  • AJAX Support: The jQuery helps you a lot to develop a responsive and feature-rich site using AJAX technology.
  • Animations: The jQuery comes with plenty of built-in animation effects which you can use in your websites.
  • Lightweight: The jQuery is very lightweight library - about 19KB in size ( Minified and gzipped ).
  • Cross Browser Support: The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
  • Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.

How to install jQuery ?

This is very simple to do require setup to use jQuery library. You have to carry two simple steps:
  1. Go to the download page to grab the latest version available.
  2. Now put downloaded jquery-1.3.2.min.js file in a directory of your website, e.g. /jquery.
The downloaded file name jquery-1.3.2.min.js may vary for your version. Your minified version would be kind of unreadable which would not have any new line or unnecessary words in it.
The jQuery does not require any special installation and very similar to JavaScript, we do not need any compilation or build phase to use jQuery.

How to use jQuery library?

Now you can include jquery library in your HTML file as follows:
<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript">
      // you can add our javascript code here 
   </script>   
</head>
<body>
........
</body>
</html>

How to call a jQuery library functions?

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
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.
To do this, we register a ready event for the document as follows:
$(document).ready(function() {
   // do stuff when DOM is ready
 });
To call upon any jQuery library function, use HTML script tags as shown below:
<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   // <![CDATA[
   $(document).ready(function() {
      $("div").click(function() {
        alert("Hello world!");
      });
   });
   // ]]>
   </script>

</head>
<body>
<div id="newdiv">
Click on this to see a dialogue box.
</div>
</body>
</html>

How to use Custom Scripts?

It is better to write our custom code in the custom JavaScript file : custom.js, as follows:
/* Filename: custom.js */
$(document).ready(function() {
  $("div").click(function() {
 alert("Hello world!");
  });
});
Now we can include custom.js file in our HTML file as follows:
<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" 
   src="/jquery/custom.js"></script>
</head>
<body>
<div id="newdiv">
Click on this to see a dialogue box.
</div>
</body>
</html>

Using Multiple Libraries:

You can use multiple libraries all together without conflicting each others. For example you can use jQuery and MooTool javascript libraries together.


jQuery - Basics


jQuery is a framework built using JavaScript capabilities. So you can use all the functions and other capabilities available in JavaScript.
This chapter would explain most basic concepts but frequently used in jQuery.

String:

A string in JavaScript is an immutable object that contains none, one or many characters.
Following are the valid examples of a JavaScript String:
"This is JavaScript String"
'This is JavaScript String'
'This is "really" a JavaScript String'
"This is 'really' a JavaScript String"

Numbers:

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings.
Following are the valid examples of a JavaScript Numbers:
5350
120.27
0.26

Boolean:

A boolean in JavaScript can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false:
Following are the valid examples of a JavaScript Boolean:
true      // true
false     // false
0         // false
1         // true
""        // false
"hello"   // true

Objects:

JavaScript supports Object concept very well. You can create an object using the object literal as follows:
var emp = {
   name: "Zara",
   age: 10
};
You can write and read properties of an object using the dot notation as follows:
// Getting object properties
emp.name  // ==> Zara
emp.age   // ==> 10

// Setting object properties
emp.name = "Daisy"  // <== Daisy
emp.age  =  20      // <== 20

Arrays:

You can define arrays using the array literal as follows:
var x = [];
var y = [1, 2, 3, 4, 5];
An array has a length property that is useful for iteration:
var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++) {
   // Do something with x[i]
 }

Functions:

A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows:
function named(){
  // do some stuff here
}
An anonymous function can be defined in similar way as a normal function but it would not have any name.
A anonymous function can be assigned to a variable or passed to a method as shown below.
var handler = function (){
  // do some stuff here
}
JQuery makes a use of anonymous functions very frequently as follows:
$(document).ready(function(){
  // do some stuff here
});

Arguments:

JavaScript variable arguments is a kind of array which has length property. Following example explains it very well:
function func(x){
  console.log(typeof x, arguments.length);
}
func();                //==> "undefined", 0
func(1);               //==> "number", 1
func("1", "2", "3");   //==> "string", 3
The arguments object also has a callee property, which refers to the function you're inside of. For example:
function func() {
   return arguments.callee; 
}
func();                // ==> func

Context:

JavaScript famous keyword this always refers to the current context. Within a function thiscontext can change, depending on how the function is called:
$(document).ready(function() {
  // this refers to window.document
});

$("div").click(function() {
  // this refers to a div DOM element
});
You can specify the context for a function call using the function-built-in methods call() andapply() methods.
The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.
function scope() {
  console.log(this, arguments.length);
}

scope() // window, 0
scope.call("foobar", [1,2]);  //==> "foobar", 1
scope.apply("foobar", [1,2]); //==> "foobar", 2

Scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
  • Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.
  • Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name:
var myVar = "global";     // ==> Declare a global variable

function ( ) {
   var myVar = "local";   // ==> Declare a local variable
   document.write(myVar); // ==> local
}

Callback:

A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.
jQuery's event system uses such callbacks everywhere for example:
$("body").click(function(event) {
   console.log("clicked: " + event.target);
 });
Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event.
Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows:
$("#myform").submit(function() {
   return false;
 });

Closures:

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.
Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them:
function create() {
  var counter = 0;
  return {
    increment: function() {
      counter++;
    },
    print: function() {
      console.log(counter);
    }
  }
}
var c = create();
c.increment();
c.print();     // ==> 1
This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming.

Proxy Pattern:

A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject.
A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows:
(function() {
  // log all calls to setArray
  var proxied = jQuery.fn.setArray;

  jQuery.fn.setArray = function() {
    console.log(this, arguments);
    return proxied.apply(this, arguments);
  };
})();
The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments)guarantees that the caller won't be able to notice the difference between the original and the proxied method.

Built-in Functions:

JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates.
Following are important JavaScript functions:
MethodDescription
charAt()Returns the character at the specified index.
concat()Combines the text of two strings and returns a new string.
forEach()Calls a function for each element in the array.
indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
length()Returns the length of the string.
pop()Removes the last element from an array and returns that element.
push()Adds one or more elements to the end of an array and returns the new length of the array.
reverse()Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
sort()Sorts the elements of an array.
substr()Returns the characters in a string beginning at the specified location through the specified number of characters.
toLowerCase()Returns the calling string value converted to lower case.
toString()Returns the string representation of the number's value.
toUpperCase()Returns the calling string value converted to uppercase.

The Document Object Model:

The Document Object Model is a tree structure of various elements of HTML as follows:
<html>
<head>
   <title>the title</title>
</head>
<body>
   <div>
      <p>This is a paragraph.</p>
      <p>This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>
Following are the important points about the above tree structure:
  • The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>.
  • The <head> and <body> elements are not only descendants, but children of <html>, as well.
  • Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.
  • The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements.

jQuery - Selectors


The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).
A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.

The $() factory function:

All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().
The factory function $() makes use of following three building blocks while selecting elements in a given document:
jQueryDescription
Tag Name:Represents a tag name available in the DOM. For example $('p')selects all paragraphs in the document.
Tag ID:Represents a tag available with the given ID in the DOM. For example$('#some-id') selects the single element in the document that has an ID of some-id.
Tag Class:Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class.
All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.
NOTE: The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $sign by jQuery name and you can use function jQuery() instead of $().

Example:

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.
<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() {
      var pars = $("p");
      for( i=0; i<pars.length; i++ ){
         alert("Found paragraph: " + pars[i].innerHTML);
      }
   });
   </script>
</head>
<body>
   <div>
      <p class="myclass">This is a paragraph.</p>
      <p id="myid">This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

How to use Selectors?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
SelectorDescription
NameSelects all elements which match with the given elementName.
#IDSelects a single element which matches with the givenID
.ClassSelects all elements which match with the given Class.
Universal (*)Selects all elements available in a DOM.
Multiple Elements E, F, GSelects the combined results of all the specified selectors E, F or G.
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("#specialID"): This selector function gets the element with id="specialID".
  • $(".specialClass"): This selector gets all the elements that have the class ofspecialClass.
  • $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.
  • $("ul li:first"): This selector gets only the first <li> element of the <ul>.
  • $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.
  • $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>
  • $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
  • $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
  • $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.
  • $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class ofmyclass.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by <p> that have no children.
  • $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
  • $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
  • $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.
  • $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.
  • $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.
  • $("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar
  • $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.
  • $("li:even"): Selects all elements matched by <li> that have an even index value.
  • $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.
  • $("li:first"): Selects the first <li> element.
  • $("li:last"): Selects the last <li> element.
  • $("li:visible"): Selects all elements matched by <li> that are visible.
  • $("li:hidden"): Selects all elements matched by <li> that are hidden.
  • $(":radio"): Selects all radio buttons in the form.
  • $(":checked"): Selects all checked boxex in the form.
  • $(":input"): Selects only form elements (input, select, textarea, button).
  • $(":text"): Selects only text elements (input[type=text]).
  • $("li:eq(2)"): Selects the third <li> element
  • $("li:eq(4)"): Selects the fifth <li> element
  • $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
  • $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
  • $("li:gt(1)"): Selects all elements matched by <li> after the second one.
  • $("p:gt(2)"): Selects all elements matched by <p> after the third one.
  • $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.
  • $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.
  • $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>
  • $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.
  • $("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.
  • $(":parent"): Selects all elements that are the parent of another element, including text.
  • $("li:contains(second)"): Selects all elements matched by <li> that contain the text second.
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.


jQuery - DOM Attributes


Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.
Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:
  • className
  • tagName
  • id
  • href
  • title
  • rel
  • src
Consider the following HTML markup for an image element:
<img id="myImage" src="image.gif" alt="An image" 
class="someClass" title="This is an image"/>
In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value.
jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.

Get Attribute Value:

The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.

Example:

Following is a simple example which fetches title attribute of <em> tag and set <div id="divid"> value with the same value:
<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() {
      var title = $("em").attr("title");
      $("#divid").text(title);
   });

   </script>
</head>
<body>
   <div>
      <em title="Bold and Brave">This is first paragraph.</em>
      <p id="myid">This is second paragraph.</p>
      <div id="divid"></div>
   </div>
</body>
</html>

Set Attribute Value:

The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:
<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() {
      $("#myimg").attr("src", "/images/jquery.jpg");
   });

   </script>
</head>
<body>
   <div>
      <img id="myimg" src="/wongpath.jpg" alt="Sample image" />
   </div>
</body>
</html>

Applying Styles:

The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:
<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() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>

Useful Attribute Methods:

Following table lists down few useful methods which you can use to manipulate attributes and properties:
MethodsDescription
attr( properties )Set a key/value object as properties to all matched elements.
attr( key, fn )Set a single property to a computed value, on all matched elements.
removeAttr( name )Remove an attribute from each of the matched elements.
hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class )Removes all or the specified class(es) from the set of matched elements.
toggleClass( class )Adds the specified class if it is not present, removes the specified class if it is present.
html( )Get the html contents (innerHTML) of the first matched element.
html( val )Set the html contents of every matched element.
text( )Get the combined text contents of all matched elements.
text( val )Set the text contents of all matched elements.
val( )Get the input value of the first matched element.
val( val )Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.
Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:
  • $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.
  • $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".
  • $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.
  • $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank
  • $("a").removeAttr("target") : This would remove target attribute of all the links.
  • $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.
  • $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected.
  • $("p").text(): Returns string that contains the combined text contents of all matched <p> elements.
  • $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> elements
  • $("p").html() : This returns the HTML content of the all matching paragraphs.
  • $("div").html("Hello World") : This would set the HTML content of all matching <div> to Hello World.
  • $("input:checkbox:checked").val() : Get the first value from a checked checkbox
  • $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons
  • $("button").val("Hello") : Sets the value attribute of every matched element <button>.
  • $("input").val("on") : This would check all the radio or check box button whose value is "on".
  • $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange, Mango and Banana.
  • $("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

jQuery - DOM Traversing


jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method.
Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions.

Find Elements by index:

Consider a simple document with the following HTML content:
<html>
<head>
<title>the title</title>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>
  • Above every list has its own index, and can be located directly by using eq(index)method as below example.
  • Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on.

Example:

Following is a simple example which adds the color to second list item.
<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() {
      $("li").eq(2).addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

Filtering out Elements:

The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax.

Example:

Following is a simple example which applies color to the lists associated with middle class:
<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() {
      $("li").filter(".middle").addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <div>
   <ul>
     <li class="top">list item 1</li>
     <li class="top">list item 2</li>
     <li class="middle">list item 3</li>
     <li class="middle">list item 4</li>
     <li class="bottom">list item 5</li>
     <li class="bottom">list item 6</li>
   </ul>
   </div>
</body>
</html>

Locating Descendent Elements :

The find( selector ) method can be used to locate all the descendent elements of a particular type of elements. The selector can be written using any selector syntax.

Example:

Following is an example which selects all the <span> elements available inside different <p> elements:
<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() {
      $("p").find("span").addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <p>This is 1st paragraph and <span>THIS IS RED</span></p>
   <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>
</body>
</html>

JQuery DOM Traversing Methods:

Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:
SelectorDescription
eq( index )Reduce the set of matched elements to a single element.
filter( selector )Removes all elements from the set of matched elements that do not match the specified selector(s).
filter( fn )Removes all elements from the set of matched elements that do not match the specified function.
is( selector )Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector.
map( callback )Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements).
not( selector )Removes elements matching the specified selector from the set of matched elements.
slice( start, [end] )Selects a subset of the matched elements.
Following table lists down other useful methods which you can use to locate various elements in a DOM:
SelectorDescription
add( selector )Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( )Add the previous selection to the current selection.
children( [selector])Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest( selector )Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents( )Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end( )Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state .
find( selector )Searches for descendent elements that match the specified selectors.
next( [selector] )Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll( [selector] )Find all sibling elements after the current element.
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] )Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
parents( [selector] )Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
prev( [selector] )Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll( [selector] )Find all sibling elements in front of the current element.
siblings( [selector] )Get a set of elements containing all of the unique siblings of each of the matched set of elements.


jQuery - CSS Methods


The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site.
Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.
Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.

Apply CSS Properties:

This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ).
Here is the syntax for the method:
selector.css( PropertyName, PropertyValue );
Here you can pass PropertyName as a javascript string and based on its value, PropertyValuecould be string or integer.

Example:

Following is an example which adds font color to the second list item.
<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() {
      $("li").eq(2).css("color", "red");
   });

   </script>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

Apply Multiple CSS Properties:

You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call.
Here is the syntax for the method:
selector.css( {key1:val1, key2:val2....keyN:valN})
Here you can pass key as property and val as its value as described above.

Example:

Following is an example which adds font color as well as background color to the second list item.
<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() {
      $("li").eq(2).css({"color":"red", 
                         "background-color":"green"});
   });

   </script>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

Setting Element Width & Height:

The width( val ) and height( val ) method can be used to set the width and hieght respectively of any element.

Example:

Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet:
<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() {
      $("div:first").width(100);
      $("div:first").css("background-color", "blue");
   });

   </script>
   <style>
   div{ width:70px; height:50px; float:left; margin:5px;
      background:red; cursor:pointer; }
  </style>
</head>
<body>
  <div></div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
</body>
</html>

JQuery CSS Methods:

Following table lists down all the methods which you can use to play with CSS properties:
MethodDescription
css( name )Return a style property on the first matched element.
css( name, value )Set a single style property to a value on all matched elements.
css( properties )Set a key/value object as style properties to all matched elements.
height( val )Set the CSS height of every matched element.
height( )Get the current computed, pixel, height of the first matched element.
innerHeight( )Gets the inner height (excludes the border and includes the padding) for the first matched element.
innerWidth( )Gets the inner width (excludes the border and includes the padding) for the first matched element.
offset( )Get the current offset of the first matched element, in pixels, relative to the document
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element.
outerHeight( [margin] )Gets the outer height (includes the border and padding by default) for the first matched element.
outerWidth( [margin] )Get the outer width (includes the border and padding by default) for the first matched element.
position( )Gets the top and left position of an element relative to its offset parent.
scrollLeft( val )When a value is passed in, the scroll left offset is set to that value on all matched elements.
scrollLeft( )Gets the scroll left offset of the first matched element.
scrollTop( val )When a value is passed in, the scroll top offset is set to that value on all matched elements.
scrollTop( )Gets the scroll top offset of the first matched element.
width( val )Set the CSS width of every matched element.
width( )Get the current computed, pixel, width of the first matched element.


jQuery - Events Handling


We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.
Following are the examples events:
  • A mouse click
  • A web page loading
  • Taking mouse over an element
  • Submitting an HTML form
  • A keystroke on your keyboard
  • etc.
When these events are triggered you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.

Binding event handlers:

Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind()method as follows:
$('div').bind('click', function( event ){
   alert('Hi there!');
});
This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.
The full syntax of the bind() command is as follows:
selector.bind( eventType[, eventData], handler)
Following is the description of the parameters:
  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • eventData: This is optional parameter is a map of data that will be passed to the event handler.
  • handler: A function to execute each time the event is triggered.

Removing event handlers:

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.
jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows:
selector.unbind(eventType, handler)

or 

selector.unbind(eventType)
Following is the description of the parameters:
  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • handler: If provided, identifies the specific listener that.s to be removed.

Event Types:

The following are cross platform and recommended event types which you can bind using JQuery:
Event TypeDescription
blurOccurs when the element loses focus
changeOccurs when the element changes
clickOccurs when a mouse click
dblclickOccurs when a mouse double-click
errorOccurs when there is an error in loading or unloading etc.
focusOccurs when the element gets focus
keydownOccurs when key is pressed
keypressOccurs when key is pressed and released
keyupOccurs when key is released
loadOccurs when document is loaded
mousedownOccurs when mouse button is pressed
mouseenterOccurs when mouse enters in an element region
mouseleaveOccurs when mouse leaves an element region
mousemoveOccurs when mouse pointer moves
mouseoutOccurs when mouse pointer moves out of an element
mouseoverOccurs when mouse pointer moves over an element
mouseupOccurs when mouse button is released
resizeOccurs when window is resized
scrollOccurs when window is scrolled
selectOccurs when a text is selected
submitOccurs when form is submitted
unloadOccurs when documents is unloaded

The Event Object:

The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.
The event object is often unneccessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certail attributes which you would need to be accessed.

The Event Attributes:

The following event properties/attributes are available and safe to access in a platform independent manner:
PropertyDescription
altKeySet to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
ctrlKeySet to true if the Ctrl key was pressed when the event was triggered, false if not.
dataThe value, if any, passed as the second parameter to the bind() command when the handler was established.
keyCodeFor keyup and keydown events, this returns the key that was pressed.
metaKeySet to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
pageXFor mouse events, specifies the horizontal coordinate of the event relative from the page origin.
pageYFor mouse events, specifies the vertical coordinate of the event relative from the page origin.
relatedTargetFor some mouse events, identifies the element that the cursor left or entered when the event was triggered.
screenXFor mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
screenYFor mouse events, specifies the vertical coordinate of the event relative from the screen origin.
shiftKeySet to true if the Shift key was pressed when the event was triggered, false if not.
targetIdentifies the element for which the event was triggered.
timeStampThe timestamp (in milliseconds) when the event was created.
typeFor all events, specifies the type of event that was triggered (for example, click).
whichFor keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right)

The Event Methods:

There is a list of methods which can be called on an Event Object:
MethodDescription
preventDefault()Prevents the browser from executing the default action.
isDefaultPrevented()Returns whether event.preventDefault() was ever called on this event object.
stopPropagation()Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
isPropagationStopped()Returns whether event.stopPropagation() was ever called on this event object.
stopImmediatePropagation()Stops the rest of the handlers from being executed.
isImmediatePropagationStopped()Returns whether event.stopImmediatePropagation() was ever called on this event object.

Event Manipulation Methods:

Following table lists down important event-related methods:
MethodDescription
bind( type, [data], fn )Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
die( type, fn )This does the opposite of live, it removes a bound live event.
hover( over, out )Simulates hovering for example moving the mouse on, and off, an object.
live( type, fn )Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
one( type, [data], fn )Binds a handler to one or more events to be executed once for each matched element.
ready( fn )Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
toggle( fn, fn2, fn3,... )Toggle among two or more function calls every other click.
trigger( event, [data] )Trigger an event on every matched element.
triggerHandler( event, [data] )Triggers all bound event handlers on an element .
unbind( [type], [fn] )This does the opposite of bind, it removes bound events from each of the matched elements.

Event Helper Methods:

jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

Trigger Methods:

Following is an example which would triggers the blur event on all paragraphs:
$("p").blur();

Binding Methods:

Following is an example which would bind a click event on all the <div>:
$("div").click( function () { 
   // do something here
});

Here is a complete list of all the support methods provided by jQuery:
MethodDescription
blur( )Triggers the blur event of each matched element.
blur( fn )Bind a function to the blur event of each matched element.
change( )Triggers the change event of each matched element.
change( fn )Binds a function to the change event of each matched element.
click( )Triggers the click event of each matched element.
click( fn )Binds a function to the click event of each matched element.
dblclick( )Triggers the dblclick event of each matched element.
dblclick( fn )Binds a function to the dblclick event of each matched element.
error( )Triggers the error event of each matched element.
error( fn )Binds a function to the error event of each matched element.
focus( )Triggers the focus event of each matched element.
focus( fn )Binds a function to the focus event of each matched element.
keydown( )Triggers the keydown event of each matched element.
keydown( fn )Bind a function to the keydown event of each matched element.
keypress( )Triggers the keypress event of each matched element.
keypress( fn )Binds a function to the keypress event of each matched element.
keyup( )Triggers the keyup event of each matched element.
keyup( fn )Bind a function to the keyup event of each matched element.
load( fn )Binds a function to the load event of each matched element.
mousedown( fn )Binds a function to the mousedown event of each matched element.
mouseenter( fn )Bind a function to the mouseenter event of each matched element.
mouseleave( fn )Bind a function to the mouseleave event of each matched element.
mousemove( fn )Bind a function to the mousemove event of each matched element.
mouseout( fn )Bind a function to the mouseout event of each matched element.
mouseover( fn )Bind a function to the mouseover event of each matched element.
mouseup( fn )Bind a function to the mouseup event of each matched element.
resize( fn )Bind a function to the resize event of each matched element.
scroll( fn )Bind a function to the scroll event of each matched element.
select( )Trigger the select event of each matched element.
select( fn )Bind a function to the select event of each matched element.
submit( )Trigger the submit event of each matched element.
submit( fn )Bind a function to the submit event of each matched element.
unload( fn )Binds a function to the unload event of each matched element.


jQuery - AJAX


AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application.

Loading simple data:

This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load()method to do the job:

Syntax:

Here is the simple syntax for load() method:
[selector].load( URL, [data], [callback] );
Here is the description of all the parameters:
  • URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.
  • data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
  • callback: A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text recieved from the server and second parameter is the status code.

Example:

Consider the following HTML file with a small JQuery coding:
<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){
          $('#stage').load('/jquery/result.html');
      });
   });
   </script>
</head>
<body>
   <p>Click on the button to load result.html file:</p>
   <div id="stage" style="background-color:blue;">
          STAGE
   </div>
   <input type="button" id="driver" value="Load Data" />
</body>
</html>
Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line:
<h1>THIS IS RESULT...</h1>
When you click the given button, then result.html file gets loaded.

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>
<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){
          $.getJSON('/jquery/result.json', function(jd) {
             $('#stage').html('<p> Name: ' + jd.name + '</p>');
             $('#stage').append('<p>Age : ' + jd.age+ '</p>');
             $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
          });
      });
   });
   </script>
</head>
<body>
   <p>Click on the button to load result.html file:</p>
   <div id="stage" style="background-color:blue;">
          STAGE
   </div>
   <input type="button" id="driver" value="Load Data" />
</body>
</html>
Here JQuery utility method getJSON() initiates an Ajax request to the specified URL/jquery/result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.json file has following json formatted content:
{
"name": "Zara Ali",
"age" : "67",
"sex": "female"
}
When you click the given button, then result.json file gets loaded.

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 dataparameter 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>
   <input type="input" id="name" size="40" /><br />
   <div id="stage" style="background-color:blue;">
          STAGE
   </div>
   <input type="button" id="driver" value="Show Result" />
</body>
</html>
Here is the code written in result.php script:
<?php
if( $_REQUEST["name"] )
{
   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
}
?> 
Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the input box. 

JQuery AJAX Methods:

You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you can use based your programming need:
Methods and Description
jQuery.ajax( options )
Load a remote page using an HTTP request.
jQuery.ajaxSetup( options )
Setup global settings for AJAX requests.
jQuery.get( url, [data], [callback], [type] )
Load a remote page using an HTTP GET request.
jQuery.getJSON( url, [data], [callback] )
Load JSON data using an HTTP GET request.
jQuery.getScript( url, [callback] )
Loads and executes a JavaScript file using an HTTP GET request.
jQuery.post( url, [data], [callback], [type] )
Load a remote page using an HTTP POST request.
load( url, [data], [callback] )
Load HTML from a remote file and inject it into the DOM.
serialize( )
Serializes a set of input elements into a string of data.
serializeArray( )
Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.

JQuery AJAX Events:

You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available:

Methods and Description
ajaxComplete( callback )
Attach a function to be executed whenever an AJAX request completes.
ajaxStart( callback )
Attach a function to be executed whenever an AJAX request begins and there is none already active.
ajaxError( callback )
Attach a function to be executed whenever an AJAX request fails.
ajaxSend( callback )
Attach a function to be executed before an AJAX request is sent.
ajaxStop( callback )
Attach a function to be executed whenever all AJAX requests have ended.
ajaxSuccess( callback )
Attach a function to be executed whenever an AJAX request completes successfully.