0% found this document useful (0 votes)
5 views40 pages

Elements of Commercial Portals

The document covers two main topics: HTML5 and XML. HTML5 introduces new features such as semantic elements, multimedia support, and enhanced form elements, while XML provides a structured format for data representation and exchange. Key aspects of both technologies include extensibility, self-descriptiveness, and the ability to validate and transform data.

Uploaded by

mirzakhizarkkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views40 pages

Elements of Commercial Portals

The document covers two main topics: HTML5 and XML. HTML5 introduces new features such as semantic elements, multimedia support, and enhanced form elements, while XML provides a structured format for data representation and exchange. Key aspects of both technologies include extensibility, self-descriptiveness, and the ability to validate and transform data.

Uploaded by

mirzakhizarkkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

BCA III Year VI Semester – Elements of Commercial Portals

Unit I - HTML 5
HTML5 is the latest version of the Hypertext Markup Language used for structuring and presenting content
on the World Wide Web. It introduces a wide range of new features, including semantic elements,
multimedia support, form enhancements, and more. Here's an overview of HTML5 and some of its key
form elements and attributes:

Introduction to HTML5
HTML5 is the fifth version of HTML, the language used to create and design web pages. It includes new
elements, attributes, and APIs (Application Programming Interfaces) that offer improved semantics,
multimedia support, and better accessibility. HTML5 is backward compatible with older HTML versions,
making it easy for developers to transition to the new standard.

Form Elements in HTML5


HTML5 introduced several new form elements to enhance user experience and simplify form validation.
Some of the key form elements include:
• Date Input (<input type="date">): Allows users to select a date from a date picker.
• Time Input (<input type="time">): Allows users to select a time from a time picker.
• Email Input (<input type="email">): Validates input as an email address.
• Number Input (<input type="number">): Validates input as a numeric value.
• Range Input (<input type="range">): Allows users to select a value from a range slider.
• Tel Input (<input type="tel">): Validates input as a telephone number.
• Color Input (<input type="color">): Allows users to select a color from a color picker.
• URL Input (<input type="url">): Validates input as a URL.
• Date-Time Input (<input type="datetime">): Allows users to select both date and time.
• Month Input (<input type="month">): Allows users to select a month and year.
• Week Input (<input type="week">): Allows users to select a week and year.

Attributes in HTML5
HTML5 also introduced new attributes to enhance form controls and improve accessibility. Some of the
key attributes include:
• Placeholder Attribute: Specifies a short hint that describes the expected value of an input field.
• Autofocus Attribute: Specifies that an input field should automatically get focus when the page
loads.
• Required Attribute: Specifies that an input field must be filled out before submitting the form.

HTML Audio and Video


HTML5 introduced native support for embedding audio and video content directly into web pages without
the need for third-party plugins like Flash. The <audio> and <video> elements allow developers to include
audio and video files using simple markup.
Example:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<video width="320" height="240" controls>
<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
BCA III Year VI Semester – Elements of Commercial Portals

HTML5 form elements and attributes examples:


1. Date Input (<input type="date">):
The date input allows users to select a date from a date picker.
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">

2. Time Input (<input type="time">):


The time input allows users to select a time from a time picker.
<label for="meeting-time">Meeting Time:</label>
<input type="time" id="meeting-time" name="meeting-time">

3. Email Input (<input type="email">):


The email input validates input as an email address.
<label for="email">Email:</label>
<input type="email" id="email" name="email">

4. Number Input (<input type="number">):


The number input validates input as a numeric value.
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="1" max="10" step="1">

5. Range Input (<input type="range">):


The range input allows users to select a value from a range slider.
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100" value="50">

6. Tel Input (<input type="tel">):


The tel input validates input as a telephone number.
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone">

7. Color Input (<input type="color">):


The color input allows users to select a color from a color picker.
<label for="color">Favorite Color:</label>
<input type="color" id="color" name="color">

8. URL Input (<input type="url">):


The URL input validates input as a URL.
<label for="website">Website:</label>
<input type="url" id="website" name="website">

9. Date-Time Input (<input type="datetime-local">):


The date-time input allows users to select both date and time.
<label for="meeting-time">Meeting Time:</label>
<input type="datetime-local" id="meeting-time" name="meeting-time">
BCA III Year VI Semester – Elements of Commercial Portals
10. Month Input (<input type="month">):
The month input allows users to select a month and year.
```html
<label for="birthday-month">Birthday Month:</label>
<input type="month" id="birthday-month" name="birthday-month">```

11. Week Input (<input type="week">):


The week input allows users to select a week and year.
```html
<label for="week">Select a week:</label>
<input type="week" id="week" name="week">
```

Attributes:
➢ Placeholder Attribute
Provides a short hint that describes the expected value of an input field.
<input type="text" name="username" placeholder="Enter your username">

➢ Autofocus Attribute
Specifies that an input field should automatically get focus when the page loads.
<input type="text" name="search" autofocus>

➢ Required Attribute
Specifies that an input field must be filled out before submitting the form.
<input type="text" name="fullname" required>

HTML Audio and Video:


<audio controls>
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<video width="320" height="240" controls>


<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
BCA III Year VI Semester – Elements of Commercial Portals

Unit II - XML
XML, or Extensible Markup Language, is a markup language that defines a set of rules for encoding
documents in a format that is both human-readable and machine-readable. It is a versatile and widely-used
standard for representing structured data, designed to be self-descriptive and easily extensible.
At its core, XML consists of a set of rules for defining custom markup languages and structuring data
hierarchically using tags enclosed in angle brackets. These tags are used to identify and organize different
types of information within the document. Additionally, XML allows for the use of attributes within tags to
provide additional metadata or properties.
XML documents are plain text files that adhere to these rules, making them platform-independent and easily
exchangeable between different systems and applications. They are commonly used for storing and
transmitting structured data across networks, as well as for configuration files, data interchange formats,
and more.
Key features of XML include:
1. Extensibility: XML is extensible, meaning that users can define their own tags and structure to
represent their data. This allows for the creation of custom markup languages tailored to specific
needs.
2. Self-Descriptiveness: XML documents are self-descriptive, as they contain both data and metadata
about the structure and meaning of the data. This metadata is provided through the use of tags,
attributes, and element hierarchy.
3. Hierarchical Structure: XML documents have a hierarchical structure consisting of nested
elements. This hierarchical structure allows for the representation of complex relationships between
different pieces of data.
4. Platform and Language Independence: XML is platform-independent and language-independent,
meaning that XML documents can be created, processed, and interpreted on any platform and by
any programming language that supports XML parsing.
5. Human Readable: XML documents are designed to be easily readable and understandable by
humans. The use of plain text format and descriptive tags makes it easy to interpret the content of
an XML document.
6. Interoperability: XML facilitates interoperability between different systems by providing a
common format for data exchange. This enables seamless communication between heterogeneous
systems, regardless of the underlying technologies.
7. Validation: XML documents can be validated against a specific schema to ensure that they conform
to a predefined structure and content rules. This helps in maintaining data integrity and consistency
across different applications.
8. Transformation: XML documents can be transformed into other formats using technologies such
as XSLT (Extensible Stylesheet Language Transformations). This allows for the conversion of XML
data into various output formats like HTML, PDF, or plain text.
BCA III Year VI Semester – Elements of Commercial Portals

XML Elements Attributes


In this XML document:
• <?xml version="1.0" encoding="UTF-8"?>: This line declares the XML version and encoding
used in the document.
• <library>: This is the root element of the XML document.
• <book>: This is a child element of <library>, representing a book. It has an attribute ISBN to
uniquely identify each book.
• <title>, <author>, <genre>, <publisher>, and <price>: These are child elements of <book>,
representing different attributes of a book.
• <first> and <last>: These are child elements of <author>, representing the first and last name of
the author.
• currency="USD": This is an attribute of the <price> element, specifying the currency in which
the price is denoted.
Example of XML documents with elements and attributes
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book ISBN="978-0-7475-3269-0">
<title>A Game of Thrones</title>
<author>
<first>George</first>
<last>RR Martin</last>
</author>
<genre>Fantasy</genre>
<publisher>
<name>Bantam Books</name>
<year>1996</year>
</publisher>
<price currency="USD">19.99</price>
</book>
<book ISBN="978-0-345-45938-6">
<title>The Fellowship of the Ring</title>
<author>
<first>J.R.R.</first>
<last>Tolkien</last>
</author>
<genre>Fantasy</genre>
<publisher>
<name>Houghton Mifflin</name>
<year>1954</year>
</publisher>
<price currency="USD">24.99</price>
</book>
</library>
BCA III Year VI Semester – Elements of Commercial Portals
XML with CSS
In XML, you can include a reference to an external CSS file or embed CSS styles directly within the
XML document using the style attribute.

Example of XML with embedded CSS:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>
<book ISBN="978-0-7475-3269-0">
<title style="font-weight: bold; color: blue;">A Game of Thrones</title>
<author>
<first>George</first>
<last>RR Martin</last>
</author>
<genre>Fantasy</genre>
<publisher>
<name>Bantam Books</name>
<year>1996</year>
</publisher>
<price currency="USD">19.99</price>
</book>
<book ISBN="978-0-345-45938-6">
<title style="font-weight: bold; color: green;">The Fellowship of the Ring</title>
<author>
<first>J.R.R.</first>
<last>Tolkien</last>
</author>
<genre>Fantasy</genre>
<publisher>
<name>Houghton Mifflin</name>
<year>1954</year>
</publisher>
<price currency="USD">24.99</price>
</book>
</library>

In this example, the style attribute is used to apply CSS styles directly to the <title> elements. The styles
include making the text bold and changing the color to blue for the first book, and green for the second
book.

Alternatively, you can also reference an external CSS file in your XML document, similar to how it's
done in HTML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="styles.css"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>
<!-- Book elements here -->
</library>
BCA III Year VI Semester – Elements of Commercial Portals
In this case, the <?xml-stylesheet?> processing instruction is used to link an external CSS file named
styles.css to the XML document. The styles defined in the CSS file will then be applied to the elements in
the XML document according to the selectors specified in the CSS.

DSO typically stands for "Data Source Object." It's a technology often associated with Microsoft
technologies, particularly with regards to database connectivity. XML can be used in conjunction with DSO
for various purposes, such as representing data structures or configurations. Below is an example of XML
with DSO:
<?xml version="1.0"?>
<library>
<book>
<title>A Game of Thrones</title>
<author>George RR Martin</author>
<genre>Fantasy</genre>
<price>19.99</price>
</book>
<book>
<title>The Fellowship of the Ring</title>
<author>J.R.R. Tolkien</author>
<genre>Fantasy</genre>
<price>24.99</price>
</book>
</library>

In this XML example, we have a simple representation of a library with two books. Each <book> element
contains child elements such as <title>, <author>, <genre>, and <price> representing different attributes
of the book.

DSO can be utilized to connect and manipulate data from this XML structure within Microsoft technologies,
such as integrating it with databases or other data sources. For instance, you might use DSO to query this
XML structure, extract information, or perform operations based on the data represented in XML. However,
the specific implementation and usage of DSO would depend on the context and technologies involved.

XML Namespacing
XML Namespacing allows elements and attributes in an XML document to be uniquely identified, even
when they have the same name, by associating them with a namespace. Namespaces are commonly used to
avoid naming conflicts between elements and attributes in XML documents, especially when integrating
multiple XML vocabularies or when defining custom XML vocabularies.

Basic example of XML Namespacing:


<?xml version="1.0"?>
<library xmlns:bk="http://example.com/books">
<bk:book>
<bk:title>A Game of Thrones</bk:title>
<bk:author>George RR Martin</bk:author>
<bk:genre>Fantasy</bk:genre>
<bk:price>19.99</bk:price>
</bk:book>
<bk:book>
<bk:title>The Fellowship of the Ring</bk:title>
BCA III Year VI Semester – Elements of Commercial Portals
<bk:author>J.R.R. Tolkien</bk:author>
<bk:genre>Fantasy</bk:genre>
<bk:price>24.99</bk:price>
</bk:book>
</library>
In this example:
• The xmlns:bk attribute in the <library> element declares a namespace prefix "bk" and associates
it with the namespace URI "http://example.com/books".
• Each element inside the <library> element prefixed with "bk:" (e.g., <bk:book>, <bk:title>)
belongs to the namespace identified by the "bk" prefix.
• The namespace URI "http://example.com/books" is an arbitrary URI used to uniquely identify the
namespace. It doesn't have to be a real URL but should be globally unique to avoid conflicts.

XML Namespacing helps in organizing and managing XML documents, especially in scenarios where
multiple XML vocabularies are combined or when elements and attributes need to be uniquely identified
to avoid conflicts. It promotes interoperability by providing a standardized way to integrate XML
vocabularies and data from different sources.

XML DTD
A Document Type Definition (DTD) is a formal declaration of the structure and constraints of an XML
document. It defines the rules and grammar that specify what elements and attributes are allowed in the
document, as well as their hierarchical relationships and data types. DTDs are used to validate XML
documents against a predefined set of rules to ensure their conformance to a specific structure.

Example of an XML DTD for a simple library system:


<!DOCTYPE library [
<!ELEMENT library (book*)>
<!ELEMENT book (title, author, genre, publisher, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT genre (#PCDATA)>
<!ELEMENT publisher (name, year)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ATTLIST book ISBN CDATA #REQUIRED>
<!ATTLIST price currency (USD|EUR) "USD">
]>

In this DTD example:


• <!DOCTYPE library [...]> declares the document type declaration for the XML document,
indicating that it conforms to the rules specified within the square brackets.
• <!ELEMENT library (book*)> defines the structure of the <library> element, stating that it can
contain zero or more <book> elements.
• <!ELEMENT book (title, author, genre, publisher, price)> specifies the structure of the <book>
element, defining that it must contain child elements <title>, <author>, <genre>, <publisher>,
and <price> in that order.
• <!ELEMENT title (#PCDATA)> defines the <title> element to contain parsed character data
(#PCDATA), meaning it can include text content.
BCA III Year VI Semester – Elements of Commercial Portals
• <!ELEMENT author (#PCDATA)>, <!ELEMENT genre (#PCDATA)>, <!ELEMENT name
(#PCDATA)>, <!ELEMENT year (#PCDATA)>, <!ELEMENT price (#PCDATA)> similarly
define other elements to contain parsed character data.
• <!ATTLIST book ISBN CDATA #REQUIRED> specifies an attribute ISBN for the <book>
element, indicating that it is of type CDATA (character data) and is required.
• <!ATTLIST price currency (USD|EUR) "USD"> defines the currency attribute for the <price>
element, restricting its value to either "USD" or "EUR", with a default value of "USD".

DTDs provide a way to formally define the structure and constraints of XML documents, facilitating
validation and ensuring consistency in data representation. However, it's worth noting that DTDs have
limitations and are gradually being replaced by other schema languages like XML Schema Definition
(XSD) and Relax NG, which offer more features and capabilities for XML validation.

XML Schemas, writing simple sheet using XSLT


XML Schema Definition (XSD) is a standard for defining the structure, content, and data types of XML
documents. It provides a more powerful and flexible way to validate XML documents compared to
Document Type Definitions (DTDs).

Example of an XSD schema for a simple library system:


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element name="book" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="genre" type="xs:string"/>
<xs:element name="publisher">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="year" type="xs:gYear"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="ISBN" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
BCA III Year VI Semester – Elements of Commercial Portals
In this XSD schema:
• The <xs:schema> element declares the XML namespace for XSD.
• The <xs:element> elements define the structure of XML elements.
• The <xs:complexType> elements define the content model of complex elements.
• The <xs:sequence> elements define the sequence of child elements within complex elements.
• The <xs:element> elements within <xs:sequence> specify the child elements of complex elements.
• The <xs:attribute> elements define attributes of elements.

This XSD schema describes a library containing books. Each book has a title, author, genre, publisher
(consisting of name and year), and price. The ISBN attribute of the book element is required.

write a simple XSLT stylesheet to transform an XML document into an HTML table:

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


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<head>
<title>Library Catalog</title>
</head>
<body>
<h1>Library Catalog</h1>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Publisher</th>
<th>Year</th>
<th>Price</th>
</tr>
<xsl:apply-templates select="library/book"/>
</table>
</body>
</html>
</xsl:template>

<xsl:template match="book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="genre"/></td>
<td><xsl:value-of select="publisher/name"/></td>
<td><xsl:value-of select="publisher/year"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
BCA III Year VI Semester – Elements of Commercial Portals
This XSLT stylesheet transforms an XML document conforming to the library schema into an HTML table,
displaying information about each book. The <xsl:template> elements define rules for matching XML
elements and generating HTML output. The <xsl:apply-templates> element is used to apply templates to
selected XML nodes, and <xsl:value-of> is used to output the value of selected XML nodes.

When applied to an XML document containing library data, this XSLT stylesheet will produce an HTML
table displaying the catalog of books.

SAX Parser, DOM Parser


SAX (Simple API for XML) Parser and DOM (Document Object Model) Parser are two commonly used
approaches for parsing XML documents in Java and other programming languages. Both parsers have their
own advantages and are suitable for different scenarios based on the requirements of the application.

SAX Parser:
SAX parsing is an event-driven parsing approach where the parser reads the XML document sequentially
and generates events as it encounters different parts of the document. These events (such as start element,
end element, characters, etc.) trigger callback methods in a handler class provided by the application.

Advantages of SAX Parser:


1. Memory efficient: SAX parser doesn't store the entire XML document in memory, making it suitable
for large XML documents.
2. Faster parsing: SAX parsing is generally faster than DOM parsing, especially for large XML files,
as it doesn't require building a tree structure in memory.
3. Low memory footprint: Since SAX parser processes XML sequentially and doesn't store the entire
document in memory, it has a lower memory footprint.

Example of SAX Parsing in Java:


import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

public class MySaxParser extends DefaultHandler {


public static void main(String[] args) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
MySaxParser handler = new MySaxParser();
saxParser.parse(new File("example.xml"), handler);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes
attributes) throws SAXException {
// Handle start element event
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// Handle character data
}
@Override
BCA III Year VI Semester – Elements of Commercial Portals
public void endElement(String uri, String localName, String qName) throws
SAXException {
// Handle end element event
}
}

DOM Parser:
DOM parsing builds an in-memory tree structure representing the entire XML document, which allows
random access to different parts of the document. This tree structure can then be traversed and manipulated
using the DOM API.
Advantages of DOM Parser:
1. Random access: DOM parsing provides random access to any part of the XML document since it
builds an in-memory tree structure.
2. Easy manipulation: Once parsed, the XML document can be easily manipulated, updated, or
modified using the DOM API.
3. Better suited for smaller documents: DOM parsing is well-suited for smaller XML documents as it
requires loading the entire document into memory.

Example of DOM Parsing in Java:


import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

public class MyDomParser {

public static void main(String[] args) throws Exception {


DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("example.xml"));

// Traverse and manipulate the document using DOM API


Element rootElement = document.getDocumentElement();
// Access child elements, attributes, etc.
}
}

if your application needs to process large XML documents efficiently with a low memory footprint,
consider using SAX parsing. On the other hand, if random access to different parts of the XML document
and easy manipulation are required, DOM parsing may be more suitable, especially for smaller XML
documents.
BCA III Year VI Semester – Elements of Commercial Portals
SOAP (Simple Object Access Protocol)
SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in the
implementation of web services. It is a messaging protocol that allows programs running on different
operating systems, platforms, or programming languages to communicate with each other over the internet.
Key components and concepts of SOAP include:
1. XML-based Messaging: SOAP messages are typically encoded in XML format, making them
human-readable and easily understandable. This XML format enables interoperability between
different systems, as XML is platform-independent and widely supported.
2. Message Structure: SOAP messages consist of an envelope, header, body, and optional fault
element. The envelope element encapsulates the entire message, while the header contains optional
metadata and the body contains the actual data being transmitted.
3. Transport Independence: SOAP messages can be transported over various protocols such as
HTTP, SMTP, or TCP. HTTP is commonly used for transporting SOAP messages over the internet,
making SOAP-based web services accessible via standard web protocols.
4. Remote Procedure Calls (RPC): SOAP supports RPC-style communication, allowing clients to
invoke methods or functions exposed by a web service, passing parameters and receiving results in
return.
5. WSDL (Web Services Description Language): WSDL is an XML-based language used to describe
the interface and functionality of web services. It defines the operations supported by the service,
the message format for each operation, and the location of the service endpoint.
6. Interoperability: SOAP is designed to facilitate interoperability between different systems,
platforms, and programming languages. By using standard protocols and XML-based messaging,
SOAP enables communication between heterogeneous systems regardless of their underlying
technologies.
7. Security: SOAP supports various security mechanisms such as SSL/TLS for transport-level security
and WS-Security for message-level security. These mechanisms help ensure the confidentiality,
integrity, and authenticity of SOAP messages exchanged between clients and servers.

Overall, SOAP provides a standardized and extensible framework for building distributed systems and web
services, enabling seamless communication and interoperability between disparate systems across the
internet. Despite the rise of alternative web service protocols like REST, SOAP remains widely used in
enterprise environments where features such as formal contract definition, strong typing, and security are
critical requirements.

Example demonstrating how SOAP messages are structured using XML:


Consider a basic SOAP request to a weather web service, where the client requests the current weather for
a specific city.

SOAP Request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:weat="http://example.com/weather">
<soapenv:Header/>
<soapenv:Body>
<weat:GetWeatherRequest>
<weat:City>New York</weat:City>
</weat:GetWeatherRequest>
</soapenv:Body>
</soapenv:Envelope>
BCA III Year VI Semester – Elements of Commercial Portals
In this example:
• <soapenv:Envelope>: The outermost element represents the SOAP envelope, encapsulating the
entire SOAP message. It declares namespaces for SOAP envelope (soapenv) and for the weather
service (weat).
• <soapenv:Header>: The optional SOAP header may contain additional metadata or authentication
information, but in this example, it's omitted.
• <soapenv:Body>: The SOAP body contains the actual payload of the message. It contains the
request to the weather service.
• <weat:GetWeatherRequest>: This element represents the specific request being made to the
weather service, in this case, a request to get weather information.
• <weat:City>: This element contains the name of the city for which the weather information is
requested (in this case, "New York").

Upon receiving this request, the weather service would process it and generate a SOAP response, typically
structured similarly to the request, but containing the requested weather information.

SOAP Response (example):


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:weat="http://example.com/weather">
<soapenv:Header/>
<soapenv:Body>
<weat:GetWeatherResponse>
<weat:City>New York</weat:City>
<weat:Temperature>25°C</weat:Temperature>
<weat:WeatherCondition>Sunny</weat:WeatherCondition>
</weat:GetWeatherResponse>
</soapenv:Body>
</soapenv:Envelope>

In the SOAP response:


• <weat:GetWeatherResponse>: Represents the response from the weather service, containing the
requested weather information.
• <weat:Temperature> and <weat:WeatherCondition>: These elements contain the temperature
and weather condition for the specified city, respectively.

These XML snippets illustrate the basic structure of SOAP messages, including the SOAP envelope, header,
body, and the payload specific to the web service operation being invoked.
BCA III Year VI Semester – Elements of Commercial Portals

Unit III & IV - jQuery


Introduction:
jQuery is a fast, small, and feature-rich JavaScript library designed to simplify the client-side scripting of
HTML. It provides a convenient API for performing common tasks such as DOM manipulation, event
handling, animation, AJAX requests, and more, across all major web browsers.

Syntax Overview:
1. Selecting Elements: jQuery uses CSS-style selectors to select elements from the DOM. For
example:
• Select by element name: $('p')
• Select by class name: $('.myClass')
• Select by ID: $('#myId')
• Select by attribute: $('[name="value"]')

2. Chaining Methods: jQuery allows method chaining, where multiple methods can be called on the
same selection. For example:
$('p').addClass('highlight').fadeOut();

3. DOM Manipulation: jQuery provides methods for manipulating the DOM:


• append(), prepend(): Insert content at the end or beginning of selected elements.
• after(), before(): Insert content after or before selected elements.
• html(), text(): Get or set HTML content or text content of elements.
• remove(): Remove selected elements from the DOM.

4. Event Handling: jQuery simplifies event handling with methods like on(), click(), change(), etc.
For example:
$('button').click(function() {
alert('Button clicked!');
});

5. Animations: jQuery provides animation effects using methods like fadeIn(), fadeOut(),
slideDown(), slideUp(), etc.

6. AJAX: jQuery simplifies AJAX requests with methods like $.ajax(), $.get(), $.post(), etc., for
fetching data from a server asynchronously.

7. Utility Functions: jQuery provides various utility functions for working with arrays, objects,
strings, etc. For example:
• $.each(): Iterate over arrays and objects.
• $.trim(): Trim whitespace from a string.
• $.extend(): Merge the contents of two or more objects together.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
BCA III Year VI Semester – Elements of Commercial Portals
<meta charset="UTF-8">
<title>jQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
// Wait for the document to be ready
$('#myButton').click(function(){
// Handle button click event
$('p').hide(); // Hide all paragraphs
});
});
</script>
</head>
<body>

<p>This is paragraph 1.</p>


<p>This is paragraph 2.</p>
<button id="myButton">Hide Paragraphs</button>

</body>
</html>
In this example:
• When the document is ready ($(document).ready()), a click event handler is attached to the
button with the ID myButton.
• When the button is clicked, all paragraphs (<p>) on the page are hidden using the hide() method.

Anatomy of jQuery Script


The anatomy of a jQuery script typically consists of the following components:
1. Include jQuery Library: Before writing jQuery code, you need to include the jQuery library in
your HTML document. You can either download the jQuery library and include it locally, or use a
CDN (Content Delivery Network) to include it from a remote server. For example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

2. Document Ready Handler: To ensure that your jQuery code executes only after the DOM
(Document Object Model) has fully loaded, you should wrap your code inside a
$(document).ready() function. This ensures that your code won't run until the HTML document is
completely parsed and loaded. For example:
$(document).ready(function() {
// jQuery code goes here
});

3. jQuery Code: Within the document ready handler, you can write your jQuery code to perform
various tasks such as selecting elements, manipulating the DOM, handling events, etc. Here's where
you'll put the core functionality of your script.

Create a simple jQuery script that changes the text of a paragraph when a button is clicked:
1. Include jQuery library in your HTML file:
<!DOCTYPE html>
<html lang="en">
BCA III Year VI Semester – Elements of Commercial Portals
<head>
<meta charset="UTF-8">
<title>First jQuery Script</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<button id="myButton">Click me</button>
</body>
</html>
2. Write jQuery code within the document ready handler to handle the button click event and
change the text of the paragraph:
<script>
$(document).ready(function() {
$('#myButton').click(function() {
$('#myParagraph').text('Text changed by jQuery!');
});
});
</script>

In this example:
• When the document is ready, the click event handler is attached to the button with the ID myButton.
• When the button is clicked, the text of the paragraph with the ID myParagraph is changed to "Text
changed by jQuery!" using the text() method.

Traversing the DOM, Selecting Elements with jQuery


Traversing the DOM and selecting elements with jQuery are fundamental tasks that allow you to manipulate
HTML elements dynamically. jQuery provides a rich set of methods for traversing and selecting elements
based on various criteria, such as element type, class, ID, attribute, position, and relationship with other
elements.

Traversing the DOM with jQuery:


jQuery provides several methods for traversing the DOM tree, allowing you to navigate through parent,
child, and sibling elements. Some common traversal methods include:
1. Parent Traversal:
• .parent(): Get the parent element of the selected element.
• .parents(): Get all ancestor elements of the selected element.
• .closest(): Get the first ancestor element that matches a selector.
2. Child Traversal:
• .children(): Get all direct child elements of the selected element.
• .find(): Get all descendant elements that match a selector.
3. Sibling Traversal:
• .siblings(): Get all sibling elements of the selected element.
• .next(): Get the next sibling element.
• .prev(): Get the previous sibling element.

Example:
<!DOCTYPE html>
<html lang="en">
<head>
BCA III Year VI Semester – Elements of Commercial Portals
<meta charset="UTF-8">
<title>Traversing the DOM with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Parent Traversal
$('#child').parent().css('border', '2px solid red');

// Child Traversal
$('#parent').children().css('background-color', 'lightblue');

// Sibling Traversal
$('#sibling').next().css('font-weight', 'bold');
});
</script>
<style>
div { margin: 10px; padding: 10px; }
</style>
</head>
<body>
<div id="parent">
Parent
<div id="child">Child</div>
<div id="sibling">Sibling</div>
</div>
</body>
</html>

In this example:
• $('#child').parent().css('border', '2px solid red'); selects the parent of the element with ID child
and adds a red border to it.
• $('#parent').children().css('background-color', 'lightblue'); selects all child elements of the
element with ID parent and sets their background color to light blue.
• $('#sibling').next().css('font-weight', 'bold'); selects the next sibling of the element with ID
sibling and sets its font weight to bold.

Selecting Elements with jQuery:


jQuery selectors allow you to easily select HTML elements based on various criteria:
• Select by element name: $('p')
• Select by class name: $('.className')
• Select by ID: $('#elementId')
• Select by attribute: $('[attributeName="value"]')
• Select by relationship: $('parent > child') (child elements directly within a parent)

Example:
$(document).ready(function() {
// Selecting elements by ID
$('#myElement').text('Selected by ID');
// Selecting elements by class
BCA III Year VI Semester – Elements of Commercial Portals
$('.myClass').css('color', 'red');
// Selecting elements by attribute
$('[name="email"]').val('example@example.com');
// Selecting elements by element name
$('input').css('border', '1px solid green');
// Selecting elements by relationship
$('ul > li').addClass('listItem');
});

In this example:
• $('#myElement').text('Selected by ID'); selects an element with ID myElement and changes its
text content.
• $('.myClass').css('color', 'red'); selects all elements with class myClass and changes their text
color to red.
• $('[name="email"]').val('example@example.com'); selects all elements with the attribute
name="email" and sets their value to example@example.com.
• $('input').css('border', '1px solid green'); selects all input elements and adds a green border to
them.
• $('ul > li').addClass('listItem'); selects all li elements that are direct children of ul elements and
adds a class listItem to them.

Refining and Filtering Selections, selecting form elements


Refining and filtering selections in jQuery allow you to further narrow down the set of elements you want
to manipulate. This can be useful when dealing with complex HTML structures or when you need to select
specific elements based on certain criteria.

jQuery provides several methods for refining and filtering selections:


1. Filtering Methods:
• .filter(selector): Reduces the set of matched elements to those that match the selector or
pass the function's test.
• .not(selector): Removes elements from the set of matched elements that match the selector.
• .first(): Reduce the set of matched elements to the first one in the set.
• .last(): Reduce the set of matched elements to the last one in the set.
• .eq(index): Reduce the set of matched elements to the one at the specified index.
• .slice(start, end): Reduce the set of matched elements to a subset specified by a range of
indices.

2. Form Elements Selection:


jQuery provides specific selectors and methods for selecting form elements:
• :input: Selects all input, textarea, select, and button elements.
• :text, :password, :radio, :checkbox, :submit, :reset, :button: Select specific types of input
elements.
• :checked: Selects all checked checkboxes and radio buttons.
• :selected: Selects all selected options within select elements.

Example:
Consider the following HTML form:
BCA III Year VI Semester – Elements of Commercial Portals
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="remember" id="rememberCheckbox">
<label for="rememberCheckbox">Remember Me</label>
<input type="submit" value="Login">
</form>

1. Filtering Example:
$(document).ready(function() {
// Filter out the input fields with the name 'username'
$('input').filter('[name="username"]').css('border', '1px solid red');

// Select the first input field


$('input').first().attr('placeholder', 'First input field');

// Select the last input field


$('input').last().attr('placeholder', 'Last input field');

// Select the second input field using eq()


$('input').eq(1).attr('placeholder', 'Second input field');
});

2. Form Elements Selection Example:


$(document).ready(function() {
// Select all input elements in the form and set their border color
$('#myForm :input').css('border', '1px solid blue');

// Select all checked checkboxes and radio buttons and set their border color
$('#myForm :checked').css('border', '1px solid green');

// Select all selected options within select elements and set their border color
$('#myForm :selected').css('border', '1px solid orange');
});

In these examples, jQuery is used to refine selections and apply CSS styles to specific form elements based
on their type, name, or state. This demonstrates how jQuery's powerful selection and filtering capabilities
can be used to manipulate form elements dynamically.

Working with selections- chaining, getters and setters


Working with selections in jQuery involves chaining methods to perform multiple operations on the same
set of elements, as well as using getters and setters to retrieve and set values of elements respectively.

Chaining Methods:
Chaining allows you to apply multiple jQuery methods to the same selection in a single statement, making
your code more concise and readable.
Example of chaining:
$(document).ready(function() {
// Chaining multiple methods
BCA III Year VI Semester – Elements of Commercial Portals
$('p').css('color', 'red').addClass('highlight').fadeOut('slow');
});

In this example:
• $('p') selects all <p> elements.
• .css('color', 'red') sets the text color of selected paragraphs to red.
• .addClass('highlight') adds the class highlight to selected paragraphs.
• .fadeOut('slow') applies a fade-out animation to selected paragraphs with a slow duration.

Getters and Setters:


jQuery provides both getters and setters for accessing and modifying element properties, attributes, and
content.
Examples of using getters and setters:
$(document).ready(function() {
// Getter: Get the value of the input field
var inputValue = $('#myInput').val();
console.log('Input value:', inputValue);

// Setter: Set the text content of the paragraph


$('p').text('New text content');

// Getter: Get the text content of the paragraph


var paragraphText = $('p').text();
console.log('Paragraph text:', paragraphText);

// Setter: Set the HTML content of the div


$('#myDiv').html('<b>New HTML content</b>');

// Getter: Get the HTML content of the div


var divHtml = $('#myDiv').html();
console.log('Div HTML:', divHtml);
});

In this example:
• .val() is used as a getter to retrieve the value of an input field with ID myInput.
• .text() is used both as a setter and a getter to set and retrieve the text content of paragraphs (<p>).
• .html() is used both as a setter and a getter to set and retrieve the HTML content of a <div>.

jQuery's chaining, getters, and setters contribute to its ease of use and expressiveness, allowing developers
to write concise and powerful code for manipulating DOM elements and their properties.

CSS, Styling and Dimensions


In jQuery, you can manipulate CSS properties, apply styles, and get dimensions of elements using various
methods provided by the library. This allows you to dynamically change the appearance and layout of your
web page based on user interactions or other events.

Manipulating CSS Properties:


jQuery provides methods to directly manipulate CSS properties of elements. You can set, get, or remove
CSS properties using these methods.
BCA III Year VI Semester – Elements of Commercial Portals

• Setting CSS Properties:


• .css(propertyName, value): Sets a CSS property to a specified value for all matched
elements.
• .addClass(className): Adds one or more classes to the matched elements' class attribute.
• .removeClass(className): Removes one or more classes from the matched elements' class
attribute.
• .toggleClass(className): Adds or removes one or more classes from the matched elements
based on their presence.

• Getting CSS Properties:


• .css(propertyName): Gets the value of a CSS property for the first matched element.
• .hasClass(className): Checks if any of the matched elements have the specified class.
• .attr(attributeName): Gets the value of the specified attribute for the first matched element.
Example:
$(document).ready(function() {
// Set CSS properties
$('p').css('color', 'red');
$('#myElement').addClass('highlight');

// Get CSS properties


var color = $('p').css('color');
console.log('Color:', color);

// Check if element has a class


if ($('#myElement').hasClass('highlight')) {
console.log('Element has class "highlight"');
}
});

Manipulating Dimensions:
jQuery provides methods to retrieve and modify the dimensions (width, height) of elements on the page.

• Getting Dimensions:
• .width(): Gets the current computed width of the first matched element, including padding
but not border or margin.
• .height(): Gets the current computed height of the first matched element, including padding
but not border or margin.
• .innerWidth(): Gets the current computed width of the first matched element, including
padding but not border, and optionally includes padding.
• .innerHeight(): Gets the current computed height of the first matched element, including
padding but not border, and optionally includes padding.
• .outerWidth(): Gets the current computed width of the first matched element, including
padding and border but not margin, and optionally includes padding and border.
• .outerHeight(): Gets the current computed height of the first matched element, including
padding and border but not margin, and optionally includes padding and border.

• Setting Dimensions:
• .width(value): Sets the width of all matched elements.
BCA III Year VI Semester – Elements of Commercial Portals
• .height(value): Sets the height of all matched elements.

Example:
$(document).ready(function() {
// Get dimensions
var width = $('#myElement').width();
var height = $('#myElement').height();
console.log('Width:', width, 'Height:', height);

// Set dimensions
$('#myElement').width(200);
$('#myElement').height(100);
});

These examples demonstrate how to manipulate CSS properties and dimensions of elements using jQuery,
providing a convenient way to dynamically style and layout elements on your web page.

Manipulating elements - getting and setting information about elements, moving,


copying, and removing elements, creating new elements
In jQuery, you can manipulate elements by getting and setting information about them, moving them within
the DOM, copying them, removing them, and creating new elements dynamically. Here are some common
methods and techniques for element manipulation:

Getting and Setting Information:


• Getting Information:
• .text(): Gets the text content of the selected element.
• .html(): Gets the HTML content of the selected element.
• .attr(): Gets the value of the specified attribute of the selected element.
• .val(): Gets the value of form elements like input, select, and textarea.

• Setting Information:
• .text(text): Sets the text content of the selected element.
• .html(html): Sets the HTML content of the selected element.
• .attr(attributeName, value): Sets the value of the specified attribute of the selected
element.
• .val(value): Sets the value of form elements like input, select, and textarea.

Example:
$(document).ready(function() {
// Getting information
var textContent = $('p').text();
console.log('Text Content:', textContent);

// Setting information
$('p').text('New text content');
});

Moving, Copying, and Removing Elements:


• Moving Elements:
BCA III Year VI Semester – Elements of Commercial Portals
• .appendTo(target): Moves the selected elements and appends them to the target element.
• .prependTo(target): Moves the selected elements and prepends them to the target element.
• .insertAfter(target): Moves the selected elements and inserts them after the target element.
• .insertBefore(target): Moves the selected elements and inserts them before the target
element.

• Copying Elements:
• .clone(): Creates a deep copy of the selected elements, including their descendants.

• Removing Elements:
• .remove(): Removes the selected elements from the DOM.
• .empty(): Removes all child nodes of the selected elements without removing the elements
themselves.
Example:
$(document).ready(function() {
// Moving elements
$('p').appendTo('#target');
$('#source').insertAfter('#target');
// Copying elements
var clone = $('#source').clone();
clone.appendTo('#container');
// Removing elements
$('#elementToRemove').remove();
$('#container').empty();
});

Creating New Elements:


• Creating Elements:
• $('<element>'): Creates a new element with the specified tag name.

• Adding Elements to the DOM:


• .append(): Appends content to the inside of the selected elements.
• .prepend(): Prepends content to the inside of the selected elements.
• .after(): Inserts content after the selected elements.
• .before(): Inserts content before the selected elements.
Example:
$(document).ready(function() {
// Creating new elements
var newDiv = $('<div>New Div</div>');

// Adding elements to the DOM


$('body').append(newDiv);
$('body').prepend('<h1>Heading</h1>');
});
BCA III Year VI Semester – Elements of Commercial Portals

jQuery – II
Manipulating attributes, utilities methods in jQuery
In jQuery, you can manipulate attributes of HTML elements, such as class, id, src, href, etc., using various
methods. Additionally, jQuery provides utility methods for performing common tasks such as iterating over
collections, merging arrays, and handling asynchronous operations.

Overview of attribute manipulation methods and some utility methods:


Manipulating Attributes:
• Getting Attributes:
• .attr(name): Gets the value of the specified attribute for the first matched element.
• .prop(propertyName): Gets the value of a property for the first matched element.

• Setting Attributes:
• .attr(name, value): Sets the value of the specified attribute for all matched elements.
• .prop(propertyName, value): Sets the value of a property for all matched elements.
• .addClass(className): Adds one or more classes to the matched elements' class attribute.
BCA III Year VI Semester – Elements of Commercial Portals
• .removeClass(className): Removes one or more classes from the matched elements' class
attribute.
• .toggleClass(className): Adds or removes one or more classes from the matched elements
based on their presence.
Example:
$(document).ready(function() {
// Getting attributes
var href = $('a').attr('href');
console.log('Href:', href);

// Setting attributes
$('img').attr('src', 'newimage.jpg');
$('input').prop('disabled', true);
$('div').addClass('highlight');
});

Utility Methods:
• Each Method:
• $.each(array, function(index, value)): Iterates over a jQuery object, executing a function
for each matched element.

• Extend Method:
• $.extend(target, object1, object2, ...): Merges the contents of two or more objects into the
target object.

• Ajax Methods:
• $.ajax(): Performs an asynchronous HTTP request.
• $.get(): Loads data from the server using an HTTP GET request.
• $.post(): Loads data from the server using an HTTP POST request.

Example:
$(document).ready(function() {
// Each method
$('li').each(function(index) {
console.log('Item ' + (index + 1) + ': ' + $(this).text());
});

// Extend method
var obj1 = { a: 1, b: 2 };
var obj2 = { b: 3, c: 4 };
var result = $.extend({}, obj1, obj2);
console.log('Merged Object:', result);

// Ajax method
$.get('example.txt', function(data) {
console.log('Data from server:', data);
BCA III Year VI Semester – Elements of Commercial Portals
});
});

Events - connecting events to elements, namespacing events, event handling, triggering event handlers,
event delegation

In jQuery, events play a crucial role in creating interactive web applications. You can connect events to
elements, handle events, namespace events for better organization, trigger event handlers programmatically,
and use event delegation to efficiently manage events on dynamically created elements. Here's an overview
of these concepts:

Connecting Events to Elements:


You can use the .on() method to connect event handlers to elements. It allows you to specify one or more
event types and the function to execute when the event occurs.
$(document).ready(function() {
// Connect click event to button
$('button').on('click', function() {
alert('Button clicked!');
});
});

Namespacing Events:
Namespacing events is a technique to organize event handlers by prefixing event types with a namespace.
This allows you to easily remove or unbind specific event handlers later.
$(document).ready(function() {
// Connect click event with namespace
$('button').on('click.myNamespace', function() {
alert('Button clicked with namespace!');
});

// Remove event handler with specific namespace


$('button').off('click.myNamespace');
});

Event Handling:
You can handle events using event methods such as .on(), .off(), .bind(), .unbind(), etc. These methods
allow you to attach event handlers, detach event handlers, and trigger events programmatically.
$(document).ready(function() {
// Connect event handler
$('input').on('keypress', function(event) {
console.log('Key pressed:', event.key);
});

// Disconnect event handler


$('input').off('keypress');
});
BCA III Year VI Semester – Elements of Commercial Portals
Triggering Event Handlers:
You can programmatically trigger event handlers using the .trigger() method. This is useful for simulating
user interactions or triggering custom events.
$(document).ready(function() {
// Connect event handler
$('button').on('click', function() {
alert('Button clicked!');
});

// Trigger event handler


$('button').trigger('click');
});

Event Delegation:
Event delegation allows you to attach a single event handler to a parent element and have it respond to
events that occur on its descendants, even if they are dynamically created after the handler is attached.
$(document).ready(function() {
// Event delegation for dynamically created elements
$('ul').on('click', 'li', function() {
alert('List item clicked!');
});

// Dynamically add list item


$('ul').append('<li>New Item</li>');
});

These examples illustrate how to work with events in jQuery, including connecting events to elements,
namespacing events, handling events, triggering event handlers, and using event delegation. Understanding
these concepts is essential for building interactive and responsive web applications.

jQuery effects - hide/show, fade, slide, animate, callback, stop


jQuery provides a range of effects to animate elements on a web page, such as hiding and showing elements,
fading elements in or out, sliding elements up or down, and custom animations using the animate() method.
You can also use callback functions to execute code after an animation completes, and the stop() method
to stop an ongoing animation.

Overview of these effects:


Hide and Show:
• .hide(): Hides the matched elements with a sliding motion.
• .show(): Displays the matched elements with a sliding motion.
$(document).ready(function() {
// Hide element with sliding motion
$('#myElement').hide();

// Show element with sliding motion


$('#myElement').show();
BCA III Year VI Semester – Elements of Commercial Portals
});
Fade:
• .fadeIn(): Fades in the matched elements.
• .fadeOut(): Fades out the matched elements.
• .fadeToggle(): Toggles between fading in and fading out the matched elements.
• .fadeTo(duration, opacity): Fades the matched elements to a specified opacity.
$(document).ready(function() {
// Fade in element
$('#myElement').fadeIn();
// Fade out element
$('#myElement').fadeOut();
// Fade toggle element
$('#myElement').fadeToggle();
// Fade to specified opacity
$('#myElement').fadeTo('slow', 0.5);
});

Slide:
• .slideDown(): Slides down the matched elements.
• .slideUp(): Slides up the matched elements.
• .slideToggle(): Toggles between sliding down and sliding up the matched elements.
$(document).ready(function() {
// Slide down element
$('#myElement').slideDown();

// Slide up element
$('#myElement').slideUp();

// Slide toggle element


$('#myElement').slideToggle();
});

Animate:
• .animate(properties, duration, easing, complete): Performs a custom animation on the matched
elements.
$(document).ready(function() {
// Custom animation
$('#myElement').animate({
width: '200px',
height: '200px',
opacity: 0.5
}, 1000, 'swing', function() {
console.log('Animation complete');
});
});

Callback:
You can specify a callback function to be executed after an animation completes.
$(document).ready(function() {
BCA III Year VI Semester – Elements of Commercial Portals
$('#myElement').fadeOut('slow', function() {
console.log('Fade out complete');
});
});

Stop:
• .stop(): Stops the currently running animation on the matched elements.
$(document).ready(function() {
$('#myElement').stop();
});

These examples demonstrate how to use jQuery effects to animate elements on a web page, including hiding
and showing elements, fading elements in or out, sliding elements up or down, and custom animations. You
can also utilize callback functions to execute code after an animation completes and the stop() method to
stop ongoing animations.

Interactions - draggable, droppable, Resizable, selectable, sortable


In jQuery UI, interactions refer to user interface behaviors that allow users to interact with elements on a
web page in various ways, such as dragging and dropping elements, resizing elements, selecting multiple
elements, and sorting elements. jQuery UI provides a set of interactions that can be easily integrated into
web applications. Here's an overview of some common interactions:

Draggable:
The draggable interaction allows you to make elements draggable by the user. You can specify options to
control the behavior of dragging, such as containment, cursor, and snap.
Example:
$(function() {
$('#draggableElement').draggable();
});

Droppable:
The droppable interaction allows you to define drop targets for draggable elements. You can specify
options to control the behavior of dropping, such as tolerance, accept, and hoverClass.
Example:
$(function() {
$('#droppableArea').droppable({
drop: function(event, ui) {
$(this).addClass('dropped');
ui.draggable.addClass('dragged');
}
});
});

Resizable:
The resizable interaction allows you to make elements resizable by the user. You can specify options to
control the behavior of resizing, such as handles, minWidth, and maxWidth.
Example:
BCA III Year VI Semester – Elements of Commercial Portals
$(function() {
$('#resizableElement').resizable();
});

Selectable:
The selectable interaction allows you to make elements selectable by the user. You can specify options to
control the behavior of selection, such as filter, cancel, and selected.
Example:
$(function() {
$('#selectableContainer').selectable();
});

Sortable:
The sortable interaction allows you to make elements sortable by the user. You can specify options to
control the behavior of sorting, such as axis, containment, and handle.
Example:
$(function() {
$('#sortableList').sortable();
});

These interactions can enhance the user experience of your web applications by providing intuitive ways
for users to interact with elements. You can customize the behavior and appearance of these interactions
using various options provided by jQuery UI.

Widgets – Accordian, DatePicker, Menu, Tabs


In jQuery UI, widgets are reusable components that provide enhanced functionality and user interface
elements for web applications. Some common widgets include Accordion, Datepicker, Menu, and Tabs.

Overview of each widget:


Accordion:
The Accordion widget allows you to create collapsible panels with multiple sections, where only one section
can be expanded at a time. Users can click on section headers to expand or collapse the corresponding
content.
Example:
$(function() {
$('#accordion').accordion();
});

DatePicker:
The DatePicker widget provides a calendar interface for selecting dates. It allows users to navigate through
months and years, select a specific date, and optionally input dates directly.
Example:
$(function() {
$('#datepicker').datepicker();
});

Menu:
BCA III Year VI Semester – Elements of Commercial Portals
The Menu widget allows you to create hierarchical menus with submenus. You can customize the
appearance and behavior of menu items, such as adding icons, tooltips, and keyboard navigation.
Example:
$(function() {
$('#menu').menu();
});

Tabs:
The Tabs widget organizes content into separate tabs, allowing users to switch between different sections
of content. Each tab panel can contain any HTML content, such as text, images, or other widgets.
Example:
$(function() {
$('#tabs').tabs();
});

These widgets provide rich and interactive user interface elements that enhance the usability and
functionality of web applications. You can customize their appearance and behavior using various options
provided by jQuery UI. Integrating these widgets into your web applications can help improve the user
experience and make your application more user-friendly.

Plugins – Using readymade plugins, create a basic plugin, writing plugins


Plugins, in the context of web development with jQuery, are pieces of code that extend the functionality of
the jQuery library. They are reusable components or modules that provide additional features or behaviors
that are not included in the core jQuery library.

Plugins are typically developed to solve specific problems or add specific functionalities to web
applications. They encapsulate complex or commonly used code into a single unit that can be easily
integrated into projects, making development more efficient and reducing code duplication.

There are thousands of jQuery plugins available, covering a wide range of functionalities such as sliders,
carousels, lightboxes, form validation, Ajax handling, animations, and much more. These plugins are often
developed by the community and shared through various platforms like GitHub, npm, or the jQuery Plugin
Registry.

Using plugins can save developers time and effort by providing pre-built solutions for common tasks,
allowing them to focus on building unique features or solving domain-specific problems in their
applications.
Using Ready-made Plugins:
1. Find a Plugin: Search for a jQuery plugin that fits your requirements on platforms like GitHub,
npm, or the jQuery Plugin Registry.
2. Include jQuery and Plugin Files: Add the jQuery library and the plugin files to your HTML
document.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="path/to/plugin.js"></script>
3. Initialize the Plugin: Initialize the plugin on the appropriate HTML element(s) using JavaScript.
<div id="myElement"></div>
<script>
$(document).ready(function() {
$('#myElement').pluginName();
BCA III Year VI Semester – Elements of Commercial Portals
});
</script>
Creating a Basic Plugin:
1. Define the Plugin Function: Create a function that defines your plugin's behavior. The function
should accept options as parameters and return this to maintain chaining.
(function($) {
$.fn.myPlugin = function(options) {
// Default options
var settings = $.extend({
color: 'red',
fontSize: '16px'
}, options);

// Plugin logic
return this.each(function() {
$(this).css({
color: settings.color,
fontSize: settings.fontSize
});
});
};
})(jQuery);
2. Use the Plugin: Call the plugin function on selected elements and pass any desired options as an
object.
$(document).ready(function() {
$('.myElements').myPlugin({
color: 'blue',
fontSize: '20px'
});
});
Writing Plugins:
1. Define the Plugin Function: Write a function that encapsulates your plugin's functionality. Use
$.fn to extend jQuery with your plugin method.
2. Handle Options: Use $.extend() to merge default options with user-defined options.
3. Implement Plugin Logic: Write the logic for your plugin inside the function. Use this.each() to
iterate over the selected elements.
4. Return this: Ensure that the plugin function returns this to maintain chaining.
5. Initialize the Plugin: Call the plugin function on selected elements in your HTML document.

By following these steps, you can either use ready-made plugins or create your own custom jQuery plugins
to add specific functionalities to your web applications.

Some examples of popular jQuery plugins along with their functionalities:


1. jQuery UI: Provides a collection of user interface interactions, effects, widgets, and themes for
building rich web applications. Examples include:
• Draggable: Allows elements to be dragged around the page.
• Droppable: Defines drop targets for draggable elements.
• Resizable: Enables resizing of elements.
• Sortable: Allows elements to be sorted via drag and drop.
BCA III Year VI Semester – Elements of Commercial Portals

2. Slick: A responsive carousel/slider plugin that supports various options and configurations for
creating slick and customizable carousels.

3. FancyBox: A lightweight and customizable lightbox plugin for displaying images, videos, or HTML
content in a modal window with various transition effects.

4. jQuery Validation Plugin: A plugin for client-side form validation that provides a robust set of
validation rules and customizable error messages.

5. Select2: Enhances HTML select boxes by adding search functionality, tagging support, infinite
scrolling, and other features to create rich and user-friendly select inputs.

6. DataTable: Allows you to enhance HTML tables by adding advanced features such as sorting,
filtering, pagination, and more, making it easy to work with large datasets.

7. Chosen: A plugin for enhancing select boxes and multiple select inputs by adding search
functionality, keyboard navigation, and customizable styling.

8. jQuery Mask Plugin: Provides a simple way to mask input fields (e.g., for formatting phone
numbers, dates, or credit card numbers) by defining input patterns.

9. jQuery ScrollTo: Allows smooth scrolling to specific elements on a page or to specific positions
within the document, enhancing navigation and user experience.

10. Waypoints: A library that triggers events when scrolling to specific elements on the page, allowing
for dynamic behavior such as lazy loading, infinite scrolling, or animations.

These are just a few examples of the many jQuery plugins available. They demonstrate the versatility and
power of jQuery in extending the functionality of web applications and enhancing user experience.
Depending on your project requirements, you can choose from a wide range of plugins to add desired
features and functionalities to your web application.
BCA III Year VI Semester – Elements of Commercial Portals

Unit V - AJAX
AJAX introduction
AJAX (Asynchronous JavaScript and XML) is a technology used to create interactive and dynamic web
applications by enabling asynchronous communication between the client and the server. It allows web
pages to request and exchange data with a server in the background without requiring the page to be
refreshed or reloaded.

Overview of AJAX and its key components:


1. Asynchronous Communication: AJAX enables asynchronous communication between the client
(typically a web browser) and the server. This means that the client can send requests to the server
and receive responses without blocking the user interface or requiring the entire page to reload.

2. XMLHttpRequest Object: In traditional web development, the primary way to interact with the
server was through full-page reloads initiated by hyperlinks or form submissions. AJAX introduced
the XMLHttpRequest (XHR) object, which allows JavaScript code to make HTTP requests to the
server asynchronously.

3. Data Exchange Formats: AJAX typically exchanges data with the server in formats such as JSON
(JavaScript Object Notation) or XML (eXtensible Markup Language). JSON has become the
preferred format due to its simplicity, lightweight nature, and ease of parsing in JavaScript.

4. DOM Manipulation: Upon receiving a response from the server, AJAX allows JavaScript to
dynamically update the content of the web page without reloading the entire page. This is often
achieved by manipulating the Document Object Model (DOM) of the webpage.

5. Event-Driven Programming: AJAX follows an event-driven programming model, where


JavaScript code listens for events such as user interactions (e.g., button clicks) or the completion of
asynchronous requests. When these events occur, appropriate actions are triggered, such as sending
AJAX requests or updating the DOM with new content.

6. Cross-Origin Resource Sharing (CORS): Due to security restrictions enforced by web browsers,
AJAX requests are subject to the same-origin policy, which prohibits requests to domains other than
the one from which the web page originated. CORS is a mechanism that allows servers to specify
which origins are permitted to access their resources via AJAX requests.

Example of AJAX Workflow:


1. The user interacts with a web page by clicking a button.
2. JavaScript code attached to the button's click event sends an AJAX request to the server.
3. The server processes the request, performs any necessary operations (e.g., querying a database,
performing calculations), and sends a response back to the client.
4. The JavaScript code receives the response and processes it, typically by updating the content of the
webpage dynamically.
5. The user sees the updated content on the webpage without the need for a full page reload.
BCA III Year VI Semester – Elements of Commercial Portals
Overall, AJAX enables web developers to create more responsive, interactive, and dynamic web
applications by facilitating seamless communication between the client and the server.

jQuery AJAX related methods


jQuery provides several methods to perform AJAX (Asynchronous JavaScript and XML) requests and
handle responses. These methods simplify the process of making asynchronous HTTP requests and
handling server responses in JavaScript. Here are some key jQuery AJAX-related methods:

1. $.ajax():
This is the most flexible method for making AJAX requests. It allows you to specify various options such
as the URL, request type (GET, POST, etc.), data to send to the server, and callbacks for success, error, and
complete events.
$.ajax({
url: 'example.com/api/data',
method: 'GET',
data: { key: 'value' },
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});

2. $.get()
This method is a shorthand for making GET requests. It takes the URL to which the request is sent and an
optional data object, and it returns the response data.
$.get('example.com/api/data', { key: 'value' }, function(response) {
console.log('Data received:', response);
});

3. $.post()
Similarly, this method is a shorthand for making POST requests. It takes the URL to which the request is
sent, data to send to the server, and a callback function to handle the response.
$.post('example.com/api/data', { key: 'value' }, function(response) {
console.log('Data received:', response);
});

4. $.getJSON()
This method is specifically for making AJAX requests for JSON data. It is a shorthand for making GET
requests with JSON as the expected response type.
$.getJSON('example.com/api/data', { key: 'value' }, function(response) {
console.log('JSON data received:', response);
});

5. $.ajaxSetup()
This method is used to set default values for future AJAX requests. It allows you to specify default settings
such as the URL, type, and headers for all AJAX requests made with jQuery.
$.ajaxSetup({
BCA III Year VI Semester – Elements of Commercial Portals
url: 'example.com/api',
type: 'POST'
});

6. $.ajaxPrefilter()
This method allows you to modify AJAX requests before they are sent to the server or responses before
they are processed. It is useful for adding custom headers, manipulating request data, or handling responses
globally.
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
// Add custom headers
options.headers = options.headers || {};
options.headers['X-CSRF-Token'] = 'your_csrf_token';
});

AJAX and Forms


AJAX (Asynchronous JavaScript and XML) can be effectively used with HTML forms to create dynamic
and interactive web applications. By incorporating AJAX into forms, you can submit form data to the server
asynchronously without requiring a full page reload, providing a smoother and more responsive user
experience.

Here's how you can utilize AJAX with forms:


1. Form Submission Using AJAX
You can use AJAX to submit form data to the server without reloading the entire page. This allows you to
validate form inputs, process data on the server, and update parts of the webpage based on the server's
response.
<form id="myForm">
<!-- Form inputs -->
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(event) {
// Prevent default form submission
event.preventDefault();
// Serialize form data
var formData = $(this).serialize();
// Send AJAX request
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
success: function(response) {
// Handle server response
console.log('Response from server:', response);
},
error: function(xhr, status, error) {
BCA III Year VI Semester – Elements of Commercial Portals
// Handle errors
console.error('Error:', error);
}
});
});
});
</script>

2. Form Validation Using AJAX:


You can use AJAX to perform form validation asynchronously by sending form data to the server for
validation and receiving validation results without refreshing the page.
<form id="myForm">
<!-- Form inputs -->
<input type="email" name="email" id="email">
<button type="submit">Submit</button>
</form>

<script>
$(document).ready(function() {
$('#myForm').submit(function(event) {
// Prevent default form submission
event.preventDefault();

// Get form data


var formData = $(this).serialize();

// Send AJAX request for validation


$.ajax({
url: 'validate.php',
type: 'POST',
data: formData,
success: function(response) {
// Handle validation response
if (response.valid) {
// Form data is valid, submit the form
$('#myForm').unbind('submit').submit();
} else {
// Display validation errors
alert('Validation Error: ' + response.error);
}
},
error: function(xhr, status, error) {
// Handle errors
console.error('Error:', error);
}
});
});
});
BCA III Year VI Semester – Elements of Commercial Portals
</script>
In both examples, we're preventing the default form submission behavior using event.preventDefault(),
serializing form data using $(this).serialize(), and sending the data to the server using AJAX. Upon
receiving a response from the server, we handle it accordingly, whether it's submitting the form or
displaying validation errors.

Integrating AJAX with forms can enhance the user experience by providing real-time feedback, reducing
page reloads, and improving overall responsiveness.

AJAX Events
In jQuery, AJAX requests trigger several events at different stages of the request's lifecycle. These events
provide hooks for executing code before or after specific actions, such as before the request is sent, when
the request completes successfully, or when an error occurs.

Overview of some common AJAX events and how to use them with suitable examples:
1. beforeSend
This event is triggered before the AJAX request is sent to the server. It allows you to modify the request
headers or perform any setup tasks.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
beforeSend: function(xhr) {
// Add custom headers
xhr.setRequestHeader('Authorization', 'Bearer token123');
},
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});

2. success
This event is triggered when the AJAX request completes successfully and the server responds with a 2xx
status code. It provides access to the response data.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
BCA III Year VI Semester – Elements of Commercial Portals

3. error
This event is triggered when an error occurs during the AJAX request, such as a network error or a server
error (status code other than 2xx). It provides information about the error.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
} });
4. complete
This event is triggered after the AJAX request completes, regardless of whether it was successful or resulted
in an error. It can be used for cleanup tasks or to execute code after the request finishes.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
},
complete: function(xhr, status) {
console.log('Request complete:', status);
}
});

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy