Web IV Unit Notes
Web IV Unit Notes
Web Technologies
XML Introduction
What is Markup?
Consider the following example of XML markup when put together in a bit
of text:
1 <message>
2 <text>Hello, world!</text>
3 </message>
This piece incorporates the markup emblem, or the labels, for example,
<message>…</message> also, <text>… </text>. The labels (tags)
<message> and </message> mark the beginning and the end of the XML
code section. The labels (tags) <text> and </text> encompass the content
Hello, world!.
The process of the invention of XML started around the 1990s with the sole
aim of integrating the definition of new text elements. XML Working Group
(Initially known as the SGML Editorial Review Board) created XML in the
year 1996. The group was led by Jon Bosak of Sun Microsystems with the
dynamic cooperation of an XML Special Interest Group (recently known as
the SGML Working Group) likewise sorted out by the W3C. Don Connolly
who filled in as the Working Group‘s contact was among the team as a
contact with the World Wide Web Consortium (W3W).
History of XML
Here are some significant XML historical milestones:
Features of XML
It represents an extensible markup language.
It was invented to be naturally engaging.
There are no predefined XML tags. You must define your
personalized tags.
XML was created to transport data, not to display that data.
The mark-up code of XML is simple for a human to understand.
The structured format, on the other hand, is simple to read and write
from programmes.
XML, like HTML, is an extensible markup language.
HTML and XML
XML Tree
Elements trees are used to create XML documents.
An XML tree begins with a root element and branches to child elements.
<root>
<child>
<subchild>…..</subchild>
</child>
</root>
To describe the relationships between elements, the terms parent, child, and
sibling are utilized.
Parents have kids. Parents exist for children. Siblings are children who are on
the same grade level (brothers and sisters).
The question is: are you ready? Consider the following example of making a
complete XML document
Markup, as <contact-info>
The text, or the character information, Great Learning and (91) 987-
3679.
Self – Describing Syntax:
<bookstore>
<book category=‖cooking‖>
</book>
1
2
3 <?xml version="1.0" encoding="UTF-8"?>
4 <bookstore>
<book category="novel">
5 <title lang="en">Two States</title>
6 <author>Chetan Bhagath</author>
7 <year>2005</year>
8 <price>300.00</price>
</book>
9 <book category="children">
10 <title lang="en">Harry Potter</title>
11 <author>J K. Rowling</author>
12 <year>2005</year>
<price>295.99</price>
13 </book>
14 <book category="web">
15 <title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
16 <year>2003</year>
17 <price>339.95</price>
18 </book>
19 </bookstore>
20
21
XML syntax alludes to the principles that decide how an XML application
can be composed. The XML syntax is extremely direct. Thereupon, this
makes XML exceptionally simple to learn. The following are the central
matters to recollect while making XML script.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
XML Document Rules
In the event that you‘ve seen HTML documents, you‘re acquainted with the
essential ideas of utilizing tags to markup the content of a document. This
segment examines the contrasts between HTML records and XML
documents. It goes over the essential principles of XML documents and talks
about the phrasing used to depict them.
One significant point about XML documents is: The XML detail requires a
parser to dismiss any XML document that doesn‘t adhere to the fundamental
principles. Virtually all HTML parsers will acknowledge messy markup,
thereby, making a theory with respect to what the developer of the document
proposed. To dodge the approximately organized wreck found in the normal
HTML document, the makers of XML chose to uphold document structure
from the earliest starting point.
1. Valid Document: Valid documents observe both the XML syntax structure
rules and the standards characterized in their DTD or composition (schema).
2. Invalid Document: Invalid documents don‘t keep the syntax structure rules
characterized by the XML particular. Once a developer characterizes some
certain rules for what a document may contain in a DTD or schema, and the
document doest observe those rules of a developer, then, that document
remains invalid.
3. Well-formed documents keep the XML syntax structure rules yet don‘t
have a DTD or pattern (schema).
- <?xml version="1.0"?>
- <!-- A well-formed document -->
- <greeting>
- Hello, World!
- </greeting>
Here comes a document that doesn‘t contain a single root element:
- <?xml version="1.0"?>
- <!-- An invalid document -->
- <greeting>
- Hello, World!
- </greeting>
- <greeting>
- Namaste, Duniya!
- </greeting>
An XML parser is designed to dismiss this document, nonetheless, of the
data, it might contain.
ii. If it plays catch-up with all the well-formedness requirements given in this
detail.
iii. For each of the parsed elements which are referred to in a direct or
indirect way in the document is well-formed
For instance,
ii. Or, there is actually one element, called the root, document element, no
portion of which shows up in the substance of some other element. For every
other element, if the beginning tag is in the substance of another element, the
end-tag is in the substance of a similar element. All the more just expressed,
the elements, delimited by the beginning-and end-tags, nest appropriately
inside one another.
XML data consists of an essential unit called an XML document, and this
particular unit is made out of elements, plus another markup in an old
package. In precise, an XML document has a wide vast assortment of data.
For instance, raw data of numbers, numbers in the textual representation of
molecular-structure, or numerical equations.
XML Declaration
The XML declaration demonstrates that the document is written in XML and
determines which variant of XML. The XML declaration, whenever
included, must be on the first line of the document. Likewise, the XML
declaration can indicate the language encoding for the document
(discretionary) and if the application alludes to external entities
(discretionary). For example, let us determine that the document utilizes
UTF-8 encoding (in spite of the fact that we don‘t generally need to as UTF-
8 is the default), and we indicate that the document alludes to external
entities by utilizing standalone=‖no‖. This isn‘t an independent document as
it depends on an external resource (for example the DTD). Despite the fact
that the XML declaration is discretionary, the W3C suggests that you
remember it for your XML documents. Regardless, you will need the XML
declaration to effectively validate your document.
Virtually all XML documents begin with an XML declaration that gives
fundamental data about the document to the parser. An XML declaration is
suggested, however not needed. Whenever it is being used in the document, it
must be the first thing. The declaration shall have up-to three name-value sets
(some people call the name-value attributes, albeit actually, they‘re most
certainly not). The adaptation is the rendition of XML utilized; at present,
this worth must be 1.0. The encoding is the character set utilized in this
document. The ISO-8859-1 character set referred to in this statement
incorporates the entirety of the characters utilized by most Western European
dialects. In the event that no encoding is indicated, the XML parser expects
that the characters are in the UTF-8 set, a Unicode standard that underpins
essentially every character and ideograph from the world‘s dialects.
i. Once the XML declaration is available in the XML, it must be put as the
mainline in the XML document.
iii. Case sensitive is the name of the parameters and values and must start
with ―<?xml>‖ where ―xml‖ is written in lower-case.
v. The request for putting the parameters is significant. The right request is
version, encoding, and standalone.
vii. The XML declaration has no end tag, for example </?xml>
<?xml>
2. XML declaration with version definition:
<?xml version=‖1‖>
3. XML declaration with all parameters defined:
For every XML document, it must contain one root element ONLY.
Eventually, other root elements will be situated within the one root element.
For instance
<root>
<child>Data</child>
<child>More Data</child>
</root>
XML statement without any boundaries
XML Tags
Evidently, the XML tags are one of the most significant parts of XML. Tags
establish and building rock of XML. They characterize the extent of a
component in XML. They can likewise be utilized to embed comment,
declare settings needed for parsing the environment, and to embed
uncommon instructions.
1. Start tag: The start of each non empty XML element is set apart by a
start tag. Consider an example below:
<address>
1. End tag: Each element that has start-tag must have an end tag.
Consider an example below:
</address>
Note: The end-tags incorporate a solidus (“/”) right before the name of an
element.
1. Empty tag: When a text appears between the start-tag and eng-tag, it
is called content. An element is called empty when it has no content.
An empty-tag can be written in the following ways:
Elements/Tags
Elements are demarcated with < and >. Like we said, element names are case
sensitive and can‘t incorporate spaces (the full character set can be found in
the specification). Therefore, attributes can be included as space-isolated
name or value pairs with values encased in quotes. (either single or double
quotes).
<sometag attrname="attrvalue">
The structure of XML
• Empty tags (for example tags with no content, and the start-tag is quickly
trailed by an end-tag) can on the other hand be spoken to by a single-tag.
These empty-tags start with ―<‖ and end with ―/>‖. As such, empty-tags are
handwriting. For instance: <br><br> is equivalent to <br/>. This means that,
while changing HTML over to XHTML, all <br> tags must be in both of the
permitted types of the empty tags.
<x><a>mmm<b>mmm</a>mmm</b></x>
Below is well-formed:
<x><a>mmm<b>mmm</b></a><b>mmm</b></x>
To Do:
XML Elements
A XML document is organized by a few XML elements, additionally called
XML-nodes or XML tags. The names of XML-elements are encased in
triangular brackets < > as appeared below
<element>
Syntax Rules for Elements and Tags
Element syntax: Each XML element should be closed either with the start
elements or end elements as appeared below
<element>....</element>
or on the other hand in basic cases, simply along these lines −
<element/>
Elements nesting: XML element may contain various XML elements as its
kids, however, the kids elements must not in any way over-lap – that‘s an
end-tag of an element must contain a similar name as that of the latest
unrivaled start-tag.
An XML document can contain just one root element. For instance, an
example given below isn‘t correct XML-document, in light of the fact that
both a and b elements happen at the high level without a root element.
<a>...</a>
<b>...</b>
The correct syntax is as follows
<root>
<a>...</a>
<b>...</b>
</root>
Case Sensitivity: XML-elements names are case sensitive. The names of
XML-components are case-touchy. That implies the name of the start-
elements and end-elements should actually be in a similar case.
For instance:
This is correct
<from>Deepak</from>
This is incorrect
The first letter of the start-tag is in small letter, while the first letter of the
end-tag is in capital letter, and hence, this is an incorrect/invalid XML.
<from>Deepak</From>
Root Element is mandatory in XML: XML-document must contain a root-
element. A root-element can contain child-elements have and sub-child
elements.
Invalid syntax:
Valid syntax:
<!ELEMENT br EMPTY>
<!ELEMENT p (#PCDATA|emph)* >
<!ELEMENT %name.para; %content.para; >
<!ELEMENT container ANY>
Element-type mustn‘t be declared more than one time.
Element Content
Element-content Models
Where each Name is the kind of an element which may show up as a child.
Because, any content-particle in a choice-list may show up in the element-
content at the area where the choice list shows up in the grammar; content
particles happening in a succession list MUST each show up in the element-
content in the order given in the list. The discretionary character following a
name or list administers whether the element or the content particles in the
list may happen at least one or more (+), at least zero or more (*), or zero or
one times (?). The absence of such an operator implies that the element or
content particle MUST show up precisely once. This syntax and meaning are
indistinguishable from those utilized in the productions in this specification.
The content of an element coordinates a content-model if and just on the off
chance that it is conceivable to follow-out a way through the content-model,
complying with the sequence, decision, and repetition operators and
marching every element in the content against an element-type in the content-
model. For similarity, it is a mistake if the content-model permits an element
to match more than one occurrence of an element-type in the content-model.
XML Attributes
Generally, an attribute determines a solitary property for the element, using a
value pair. An XML element can have at least one or more attributes. For
instance −
Normally, attribute names are portrayed without quotes. In the same vein,
attribute values ought to reliably appear in the quotes. The following example
displays invalid xml linguistic-structure
<a b = x>....</a>
In the above accentuation, the property assessment isn‘t portrayed in quotes.
Talking about XML attributes, let us see the sentence structure of properties.
An underlying-tag in XML can have credits, the traits are name and worth
sets.
Let us take hardly additional guides for see authentic and invalid cases of
qualities.
A tag can at least contain or more name and worth sets, at any rate two
property names cannot be same.
<a b = x>....</a>
In the above punctuation, the property estimation isn‘t characterized in
quotes.
Invalid syntax:
<?xml version= ―1.0‖ encoding=―ISO-8859-1‖?>
<note date=02/02/02>
<to>Deepak</to>
<from>Spoorthi</from>
</note>
Valid syntax:
<?xml version= ―1.0‖ encoding=―ISO-8859-1‖?>
<note date=‖02/02/02‖>
<to>Deepak</to>
<from>Spoorthi</from>
</note>
It will make a wrong document; the date attribute in the note isn‘t quoted.
Declarations of Attribute-List
Types of Attributes
XML attribute types are of three kinds: a string type, a set of tokenized types,
and enumerated types. The string type may take any literal string as a value;
the tokenized types are more constrained. The validity constraints noted in
the grammar are applied after the attribute value has been normalized as
described in 3.3.3 Attribute-Value Normalization.
Attribute Defaults
<!ENTITY d ―
‖>
<!ENTITY a ―
‖>
<!ENTITY da ―
‖>
Another thing to notice is: The previous example isn‘t correct/invalid (but
rather well-formed), if a is declared to remain type of NMTOKENS.
Special Attributes
Compare the two examples below. The markup at the top is legal in HTML,
but not in XML. To do the equivalent in XML, you have to give the attribute
a value, and you have to enclose it in quotes. Look at the two examples
beneath. The mark-up at the top is valid in HTML, yet not in XML. To do the
identical in XML, you need to give the attribute a value, and you need to
encase it in ―quotes‖.
1. <!– NOT legal XML markup –> Example 1
2. <ol compact>
3. <!– legal XML markup –> Example 2
4. <ol compact=‖yes‖>
You can utilize either single or double quotes, similarly insofar as you‘re
consciously steady. In the event that the attribute has a single or double
quote, you could utilize the other sort of quote to encompass the value (as in
name=‖Deepak‘s vehicle‖), or utilize the elements " for a double quote
and ' for a single-quote. An entity is a symbol, for example, ",
that the XML parser replaces with other text, for example, ―.
We might not have fully covered in details the concept of DTDs and how it
works, yet there‘s one more essential topic to cover here: Defining attributes.
You can characterize attributes for the elements that will show up in your
XML-document. Using an DTD, you can likewise:
Assume that you need to change the DTD to make state an attribute of the
<city> element. Here‘s the means by which to do that:
This characterizes the <city> element as in the past, yet the reviewed
example additionally utilizes an ATTLIST declaration to list the attributes of
the elements. The name city inside the attribute-list tells the parser that these
attributes are characterized for the <city> element. The name-state is the
name of the attribute, and the watchwords CDATA and #REQUIRED tell the
parser that the state attribute contains text and is required (if it‘s
discretionary, CDATA #IMPLIED will work).
At last, DTDs permit you to characterize default values for attributes and
identify the entirety of the correct values for an attribute:
To cap it all, the example here demonstrates that it just backings addresses
from the conditions of Arizona (AZ), California (CA), Nevada (NV), Oregon
(OR), Utah (UT), and Washington (WA), and that the default state is
California. Consequently, you can do a restricted type of data-validation.
While this is a valuable function, it‘s a little subset of how you can deal with
XML-schemas.
XML Comments
Comments may show up anyplace in a document outside other mark-up;
moreover, they may show up inside the document-type declaration at places
permitted by the grammar. They‘re not part of the document‘s character
data; an XM- processor may, yet needn‘t, make it feasible for an application
to recover the text of comments. For similarity, the string ‖ – ‖ (double-
hyphen) mustn’t happen inside comments.] Parameter substance
references mustn’t be perceived inside comments.
Comments can show up anyplace in the document; they can even show up
before or after the root element. A comment starts with <!- – and closes with
– >. A comment cannot contain a double hyphen ( — ) aside from toward the
end; with that special case, a comment can contain anything. Above all, any
mark-up inside a comment is overlooked; only if you need to eliminate a
huge section of a XML-document, essentially enclose that section by a
comment. (To reestablish the commented-out section, essentially eliminate
the comment tags.)
<?cocoon-process type=‖sql‖?>
Anyplace the XML processor finds the string &dw;, it replaces the entity
with the string developerWorks. The XML-spec additionally characterizes
five entities you can use instead of different special characters.
Character Reference
On the off chance that the character reference starts with ‖ &#x ―, the digits
and letters up to the ending ; give a hexadecimal representation of the
character‘s code point in ISO/IEC 10646. Again, if it starts just with ‖ &# ―,
the digits up to the ending ; give a decimal representation of the character‘s
code point.
Entity Reference
[WFC: No Recursion]
[WFC: No Recursion]
[WFC: In DTD]
<!ENTITY % ISOLat2
%ISOLat2;
CDATA Sections
CDATA Sections: CDATA sections may happen anyplace where character-
data may happen; they are utilized to get away from blocks of text containing
characters which would somehow or be perceived as mark-up. The sections
of CDATA start with the string ‖ <![CDATA[ ‖ and end with the string ‖ ]]>
―:].
CDATA Sections:
<![CDATA[<greeting>Hello, world!</greeting>]]>
Processing XML
The processing instructions start with <? and, end with ?>. Processing
instructions are guidelines for the XML-processor. Processing instructions
aren‘t incorporated with the XML-recommendation. Or maybe, they‘re
processor-dependant so not all processors see all processing instructions. Our
example is a typical processing-instruction that numerous processors
understand. The instructions to the processor are to utilize an external style-
sheet.
For instance:
Encoding XML
Encoding is the way toward converting unicode characters into their identical
binary representation. At the point when the XML-processor peruses a XML-
document, it encodes the document contingent upon the type of encoding.
Consequently, we have to indicate the type of encoding in the XML
declaration.
Types of encoding
1. UTF-8
2. UTF-16
UTF represents UCS Transformation Format, and UCS itself implies
Universal Character Set. The number 8 or 16 alludes to the number of bits
used to represent a character. They are either 8(1 to 4 bytes) or 16(2 or 4
bytes). For the documents without encoding data, UTF-8 is set by default.
Validation in XML
Validation is defined as a process by which an XML-document is validated.
An XML-document is said to be valid if its contents coordinate with the
elements, attributes and related-document type declaration (DTD), and if the
document conforms to the limitations expressed in it. Validation is managed
in two different ways by the XML parser.
They are:
Example:
1
2 Following is a case of a well-formed XML-document:
3 <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
4 <!DOCTYPE address
5 [
<!ELEMENT address (name,company,phone)>
6 <!ELEMENT name (#PCDATA)>
7 <!ELEMENT company (#PCDATA)>
8 <!ELEMENT phone (#PCDATA)>
]>
9 <address>
10 <name>Deepak Kumar</name>
11 <company>GreatLearning</company>
12 <phone>91 123-4567</phone>
</address>
13
14
The above example is said to be well-formed as –
XML Namespaces
In XML, the names of the tags used are defined by the developer. While
mixing the XML documents from different XML applications, this naming
might result in conflicts. So, XML namespaces provide a method to avoid
this issue of element name conflicts.
<table>
<tr>
<td>Table</td>
<td>Chair</td>
</tr>
</table>
The following XML code carries the information about a table (Shape):
<table>
<name>Rectangle</name>
<length>100</length>
<width>60</width>
</table>
If the above XML code fragments were to be added together, it would result
in a name conflict as both contain an element , but the content and meaning
of both the elements are different.
An XML application or a user will not be able to know how to handle such
differences.
The following code carries the data of both HTML Table and Shape Table:
<t:table>
<t:tr>
<t:td>Table</t:td>
<t:td>Chair</t:td>
</t:tr>
</t:table>
<s:table>
<s:name>Rectangle</s:name>
<s:length>100</s:length>
<s:width>60</s:width>
</s:table>
The example given above will have no conflict as both the <table> elements
have different names.
XML Parser
The XML parser is a package or a software library that provides an interface
for the applications of clients to work with XML documents. It may validate
the XML documents and checks for a proper format for the XML document.
Programs use XML with the help of an XML parser.
Types of parsers:
1. DOM Parser
2. SAX Parser
3. JDOM Parser
4. StAX Parser
5. XPath Parser
6. DOM4J Parser
DOM Parser
The Document Object Model (DOM) parser loads the document‘s complete
contents and creates its entire hierarchical tree in the memory to parse a
document. DOM parser is officially recommended by the World Wide Web
Consortium (W3C).
Simple API for XML (SAX) does not load the complete document in the
memory; instead, it parses the document on event-based triggers. No parse
trees are created by SAX Parser. SAX is a streaming interface for XML, i.e.
that when the XML document being processed an element and attribute,
applications using SAX receive event notifications at a time in chronological
order, starting from the beginning of the XML document and ending with the
closing of the ROOT element.
StAX Parser
It parses in the same way as the SAX parser but in a more efficient manner.
XPath Parser
DOM4J Parser
<!DOCTYPE html>
<html>
<body>
<p id="example"></p>
<script>
text = "<mall><shop>" +
"<name>Everyday Items</name>" +
"<item>bucket</item>" +
"<price>50</price>" +
"</shop></mall>";
<--parser creates a new XML DOM object using the text string-->
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("example").innerHTML =
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
XML DTD
Document Type Definition (DTD) defines the legal attributes and elements
along with the structure of an XML document. An XML document is well-
informed if the syntax is correct, but the XML Document that gets validated
against a DTD is both well-informed and valid.
<note>
<to>Chanchal</to>
<from>Harshit</from>
<heading>Message</heading>
XML DTD
Note.dtd:
]>
XML Schema
XML Schema, also known as XML Schema Definition (XSD), is used to
describe and validate the structure and content of XML data. It defines
attributes, elements and data types. It is similar to DTD but provides more
control over the XML structure.
</xs:sequence>
</xs:complexType>
</xs:element>
XML Schema Data Types
XML DOM
The Document Object Model (DOM) is XML‘s foundation. XML documents
contain a hierarchy of informative units known as nodes; DOM defines those
nodes and their relationships.
The XML DOM, on the other hand, includes an API that allows a developer
to add, modify, move, or remove nodes in the tree at any time throughout the
development process.
Contents of sample.html
<!DOCTYPE html>
1 <html>
2 <body>
3 <h1>Example for DOM </h1>
4 <div>
<b>Name:</b> <span id = "name"></span><br>
5 <b>Company:</b> <span id = "company"></span><br>
6 <b>Phone:</b> <span id = "phone"></span>
7 </div>
<script>
8 if (window.XMLHttpRequest)
9 {// code for IE7+, Firefox, Chrome, Opera, Safari search engines
10 xmlhttp = new XMLHttpRequest();
11 }
else
12 {// code for IE6, IE5 search engines
13 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
14 }
15 xmlhttp.open("GET","/xml/address.xml",false); // used to fetch data
xmlhttp.send();
16 xmlDoc = xmlhttp.responseXML;
17
18 document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
19 document.getElementById("company").innerHTML=
20
21 xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
22 document.getElementById("phone").innerHTML=
23 xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
24 </body>
25 </html>
26
27
28
29
30
31
32
Content in address, the XML file is as follows:
1
<?xml version = "1.0"?>
2 <contact-info>
3 <name>Karuna </name>
4 <company>Cerner</company>
<phone>(91)8364682929</phone>
5 </contact-info>
6
Now, retain these two files, sample.html and address.xml, in the same
directory /XML and run the sample.html file in any browser. This should
result in the output shown below.
Output:
JavaScript
Loosely typed scripting language.
JavaScript function is called when an event occurs in a page.
Glue for the whole AJAX operation.
DOM
API for accessing and manipulating structured documents.
Represents the structure of XML and HTML documents.
CSS
Allows for a clear separation of the presentation style from the content and may be
changed programmatically by JavaScript
XMLHttpRequest
JavaScript object that performs asynchronous interaction with the server.
AJAX - Examples
Here is a list of some famous web applications that make use of AJAX.
Google Maps
A user can drag an entire map by using the mouse, rather than clicking on a
button.
https://maps.google.com/
Google Suggest
As you type, Google offers suggestions. Use the arrow keys to navigate the
results.
https://www.google.com/webhp?complete=1&hl=en
Gmail
Gmail is a webmail built on the idea that emails can be more intuitive, efficient,
and useful.
https://gmail.com/
Standard Example
Standard
* =
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
</body>
</html>
In the above JavaScript code, we try three times to make our XMLHttpRequest
object. Our first attempt −
ajaxRequest = new XMLHttpRequest();
It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more
times to make the correct object for an Internet Explorer browser with −
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
If it doesn't work, then we can use a very outdated browser that doesn't support
XMLHttpRequest, which also means it doesn't support AJAX.
Most likely though, our variable ajaxRequest will now be set to
whatever XMLHttpRequest standard the browser uses and we can start sending
data to the server. The step-wise AJAX workflow is explained in the next
chapter.
AJAX - Action
This chapter gives you a clear picture of the exact steps of AJAX operation.
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
Assume you enter Zara in the userid box, then in the above request, the URL is
set to "validate?id = Zara".
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
<body>
<div id = "userIdMessage"><div>
</body>
If you have understood the above-mentioned seven steps, then you are almost
done with AJAX. In the next chapter, we will see XMLHttpRequest object in
more detail.
AJAX - XMLHttpRequest
The XMLHttpRequest object is the key to AJAX. It has been available ever
since Internet Explorer 5.5 was released in July 2000, but was not fully
discovered until AJAX and Web 2.0 in 2005 became popular.
XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript,
VBScript, and other web browser scripting languages to transfer and manipulate
XML data to and from a webserver using HTTP, establishing an independent
connection channel between a webpage's Client-Side and Server-Side.
The data returned from XMLHttpRequest calls will often be provided by back-
end databases. Besides XML, XMLHttpRequest can be used to fetch data in
other formats, e.g. JSON or even plain text.
You already have seen a couple of examples on how to create an
XMLHttpRequest object.
Listed below are some of the methods and properties that you have to get
familiar with.
XMLHttpRequest Methods
abort()
Cancels the current request.
getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
getResponseHeader( headerName )
Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD".
Other HTTP methods such as "PUT" and "DELETE" (primarily used in
REST applications) may be possible.
The "async" parameter specifies whether the request should be handled
asynchronously or not. "true" means that the script processing carries on
after the send() method without waiting for a response, and "false" means
that the script waits for a response before continuing script processing.
send( content )
Sends the request.
setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Properties
onreadystatechange
An event handler for an event that fires at every state change.
readyState
The readyState property defines the current state of the XMLHttpRequest
object.
The following table provides a list of the possible values for the
readyState property −
State Description
readyState = 0 After you have created the XMLHttpRequest object, but before
you have called the open() method.
readyState = 1 After you have called the open() method, but before you have
called send().
readyState = 2 After you have called send().
readyState = 3 After the browser has established a communication with the
server, but before the server has completed the response.
readyState = 4 After the request has been completed, and the response data has
been completely received from the server.
responseText
Returns the response as a string.
responseXML
Returns the response as XML. This property returns an XML document
object, which can be examined and parsed using the W3C DOM node tree
methods and properties.
status
Returns the status as a number (e.g., 404 for "Not Found" and 200 for
"OK").
statusText
Returns the status as a string (e.g., "Not Found" or "OK").
Dojo Toolkit
Dojo Toolkit is an open-source modular JavaScript library designed to ease the rapid
development of cross-platform, JavaScript/Ajax-based applications and web sites.
The Dojo Toolkit is divided into several main packages that would constitute a full
distribution of Dojo Toolkit. Those main packages are:
dojo - Sometimes referred to as the ―core‖, this is the main part of Dojo and the most
generally applicable packages and modules are contained in here. The core covers a
wide range of functionality like AJAX, DOM manipulation, class-type
programming, events, promises, data stores, drag-and-drop and internationalization
libraries.
dijit - An extensive set of widgets (user interface components) and the underlying
system to support them. It is built fully on-top of the Dojo core.
dojox - A collection of packages and modules that provide a vast array of
functionality that are built upon both the Dojo core and Dijit. Packages and
modules contained in DojoX will have varying degrees of maturity, denoted within
the README files of each package. Some of the modules are extremely mature
and some are highly experimental.
util - Various tools that support the rest of the toolkit, like being able to build, test
and document code.
One of the long term objectives of the Dojo Toolkit is to continue to make packages more
vibrant and not necessarily require packages to exist within DojoX. Some of the packages
that are currently part of this community are: