5 Ajax And Xml

Web Technology · Unit 5 · 7 hrs

AJAX and XML

Exam-focused notes for AJAX and XML (Web Technology, CSC329): what the TU syllabus asks and how it has actually been tested, with 11 solved past questions from this unit.

AJAX and XML in short

This unit covers two technologies that let a page exchange data behind the scenes: AJAX, which updates a page without a full reload, and XML, a self-describing data format together with the schema and transformation languages built around it.

AJAX and XML: notes

Basics of AJAX

AJAX (Asynchronous JavaScript And XML) is a set of development techniques, not a language or framework, for building web pages that update without a full page reload. Using AJAX, a page can request data from a server, receive it in the background, and update just the affected part of the page, all while the user keeps interacting with the rest of it. AJAX itself combines three existing technologies: the browser's built-in XMLHttpRequest object (to talk to the server), and JavaScript together with the HTML DOM (to use and display the result). Its usual sequence is: an event occurs on the page (a button click); JavaScript creates an XMLHttpRequest object; that object sends a request to the server; the server processes it and sends a response; JavaScript reads the response and updates the page. Its main advantages are speed (only the changed data travels, not a whole new page), a more responsive and asynchronous user experience, faster form validation, and lower bandwidth use since a full page is not reloaded for a small change. Its drawbacks include content that is harder for search engines to index if it depends entirely on AJAX to appear, and the fact that despite the name, AJAX is commonly used with JSON rather than XML today, exactly because JSON is lighter to parse.

const xhr = new XMLHttpRequest();
xhr.open("GET", "ajax_info.txt", true);
xhr.onload = function() {
  if (xhr.status === 200) {
    document.getElementById("demo").innerHTML = xhr.responseText;
  }
};
xhr.send();

The open(method, url, async) method prepares the request (method is GET or POST, async is true for an asynchronous call), and send() dispatches it, carrying a string body when the method is POST. Once the response arrives, responseText gives it as a plain string and responseXML gives it as a parsed XML DOM object.

Introduction to XML and its Application

XML (Extensible Markup Language) was designed to store and transport data in a form that is both human-readable and machine-readable. Unlike HTML, XML has no predefined tags; a document's author defines whatever tag names fit the data being described, which is why XML is described as extensible. XML is platform-independent and language-independent, and, importantly, it is designed to carry data, not to say how that data should be displayed. Its main benefits are simplicity (easy for both people and programs to read), openness (an open W3C standard), extensibility (no fixed vocabulary), self-description (a document carries its own structure), separation of content from presentation, and the ability to embed practically any data type. XML underlies formats used across the web: configuration files, RSS feeds, SOAP messages, Microsoft Office's .docx/.xlsx files, and, closer to this syllabus, the schema and transformation languages covered later in this unit.

What this unit covers

  • Basics of AJAX
  • Introduction to XML and its Application
  • Syntax Rules for creating XML document
  • XML Elements
  • XML Attributes
  • XML Tree
  • XML Namespace
  • XML schema languages: Document Type Definition(DTD), XML Schema Definition (XSD)
  • XSD Simple Types
  • XSD Attributes
  • XSD Complex Types
  • XML Style Sheets (XSLT)
  • XQuery

XSD Complex Types

2082 · 10 marks

What is the use of XML? Create an XML file having complex type elements containing other elements and text. At least one element should contain an attribute. Similarly, there should be elements containing string, integer and date type values. Now write the equivalent XSD for the XML.[10]

Show solved answer

XML: Uses, XML File with Complex Types, and Equivalent XSD


Uses of XML

XML (eXtensible Markup Language) is used for:

  • Data storage and transport between applications and systems
  • Platform-independent data exchange over the internet
  • Configuration files for software applications (e.g., web.xml, pom.xml)
  • Web services (SOAP, REST use XML for message formatting)
  • Document representation (e.g., Office documents, RSS feeds)
  • Database-like storage for small structured datasets
  • Separating data from presentation (used with XSLT for transformation)

XML File with Complex Type Elements

The following XML file represents a Library with Book records. It includes:

  • Complex type elements containing other elements and text
  • At least one element with an attribute
  • Elements with string, integer, and date type values
<?xml version="1.0" encoding="UTF-8"?>
<library>

    <book id="B001">
        <title>Introduction to Programming</title>
        <author>Dennis Ritchie</author>
        <publisher>
            <name>TechPress</name>
            <country>USA</country>
        </publisher>
        <price>1500</price>
        <publishedDate>2020-06-15</publishedDate>
        <available>true</available>
    </book>

    <book id="B002">
        <title>Data Structures and Algorithms</title>
        <author>Thomas Cormen</author>
        <publisher>
            <name>MIT Press</name>
            <country>USA</country>
        </publisher>
        <price>2200</price>
        <publishedDate>2018-03-10</publishedDate>
        <available>false</available>
    </book>

</library>

Explanation of the XML

Element/AttributeTypeDescription
<library>Root elementContains all book records
<book id="B001">Complex type with attributeid is an attribute of book
<title>, <author>, <name>, <country>StringText values
<price>IntegerNumeric value
<publishedDate>DateDate in YYYY-MM-DD format
<publisher>Complex typeContains child elements <name> and <country>

Equivalent XSD (XML Schema Definition)

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

    <!-- Root Element -->
    <xs:element name="library">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="book" type="bookType"
                            minOccurs="1" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <!-- Complex Type: bookType -->
    <xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="title"         type="xs:string"/>
            <xs:element name="author"        type="xs:string"/>
            <xs:element name="publisher"     type="publisherType"/>
            <xs:element name="price"         type="xs:integer"/>
            <xs:element name="publishedDate" type="xs:date"/>
            <xs:element name="available"     type="xs:boolean"/>
        </xs:sequence>
        <!-- Attribute for book element -->
        <xs:attribute name="id" type="xs:string" use="required"/>
    </xs:complexType>

    <!-- Complex Type: publisherType (nested complex type) -->
    <xs:complexType name="publisherType">
        <xs:sequence>
            <xs:element name="name"    type="xs:string"/>
            <xs:element name="country" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

</xs:schema>

Explanation of the XSD

XSD ComponentPurpose
xs:schemaRoot element of every XSD file
xs:elementDeclares an XML element
xs:complexTypeDefines elements that contain child elements or attributes
xs:sequenceChild elements must appear in the defined order
xs:attribute use="required"Declares id as a required attribute of <book>
xs:stringSimple type for text values (title, author, name, country)
xs:integerSimple type for whole number values (price)
xs:dateSimple type for date values (publishedDate)
xs:booleanSimple type for true/false values (available)
minOccurs / maxOccursControls how many times an element can appear

Note: XSD is like DTD but provides more control on XML structure. It supports predefined simple types such as xs:integer, xs:boolean, xs:string, and xs:date, and uses complex types as containers for other element definitions to build a hierarchy of elements.

Open this answer on its own page →

Syntax Rules for creating XML document

2081 · 10 marks

Describe the rules for creating XML document. Create a XML file with simple type and elements with attribute and nested elements. Write its equivalent XSD.[10]

The following rules must be followed: Rule 1: Every XML document must have exactly one Root Element All XML content must be enclosed within a single root element. Rule 2: All Tags Must Be Closed Every opening tag must have a corresponding closing tag. Rule 3: All Tags Must Be Properly Nested Tags...

Open this answer on its own page →

2080 · 10 marks

How XML is different from HTML? Write XML script to create XML document containing element Person having sub elements Age, Name and Pincode. Write equivalent XSD for validating restrictions on the elements as the Age should be between 10 and 20, the Name should be only accepting either Ram or Shyam and the pincode should be 3 digit.[10]

Feature XML HTML --------- Purpose Designed to store and transport data Designed to display data Tag Definition Tags are user-defined (custom tags) Tags are predefined and fixed Case Sensitivity Tags are case-sensitive (<Name and <name are different) Tags are not case-sensitive Closing Tags All t...

Open this answer on its own page →

XML Style Sheets

2081 · 5 marks

How can you transform XML document into HTML using XSLT. Support your answer with an example. [5]

XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other formats such as HTML for web pages, plain text, or other XML documents. The original document is not changed; rather, a new document is created based on the content of an existing one. XS...

Open this answer on its own page →

Introduction to XML and its Application

2080 · 5 marks

What is XML? Why is it called extensible? Mention the use of XML. [5]

--- XML (eXtensible Markup Language) is a markup language designed to store, transport, and describe data in a structured, human-readable, and machine-readable format. It was developed by the W3C (World Wide Web Consortium) and became a W3C recommendation in 1998. XML uses tags (similar to HTML) ...

Open this answer on its own page →

2076 · 5 marks

What is XML? Create an XML file containing records of employee having elements of simple and complex types. [5]

XML (eXtensible Markup Language) is a markup language designed to store and transport data in a structured, human-readable, and machine-readable format. Unlike HTML, XML does not have predefined tags; instead, users define their own tags to describe the data. XML is platform-independent and is wi...

Open this answer on its own page →

Basics of AJAX

2080 · 5 marks

What is XMLHttpRequest object? Write HTML script with AJAX showing the use of XMLHttpRequest object. [5]

Show solved answer

XMLHttpRequest Object and AJAX

XMLHttpRequest Object

The XMLHttpRequest (XHR) object is a built-in browser object that is used to exchange data with a web server in the background. It is the core component of AJAX technology. Using the XMLHttpRequest object, a web page can request data from a server and update only a portion of the page without reloading the entire page.

Syntax to create an XMLHttpRequest object:

var xhr = new XMLHttpRequest();

Key Methods of XMLHttpRequest Object

MethodDescription
open(method, url, async)Specifies the type of request (GET/POST), the server URL, and whether the request is asynchronous (true) or synchronous (false)
send()Sends the request to the server (used for GET)
send(string)Sends the request to the server (used for POST)

Key Properties of XMLHttpRequest Object

PropertyDescription
responseTextReturns the server response as a JavaScript string
responseXMLReturns the server response as an XML DOM object
onreadystatechangeDefines a function to be called when the readyState changes
readyStateHolds the status of the request (0 to 4)
statusReturns the HTTP status code (e.g., 200 for OK)

HTML Script with AJAX Using XMLHttpRequest Object

<!DOCTYPE html>
<html>
<head>
    <title>AJAX XMLHttpRequest Example</title>
    <script>
        function loadData() {
            // Step 1: Create XMLHttpRequest object
            var xhr = new XMLHttpRequest();

            // Step 2: Define what happens when response is received
            xhr.onreadystatechange = function() {
                // readyState 4 means request is done
                // status 200 means response is OK
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Step 5: Update the page with the server response
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            };

            // Step 3: Open the request (GET method, async = true)
            xhr.open("GET", "ajax_info.txt", true);

            // Step 4: Send the request to the server
            xhr.send();
        }
    </script>
</head>
<body>
    <h2>AJAX Demo Using XMLHttpRequest</h2>

    <button onclick="loadData()">Click to Load Data</button>

      

    <!-- This div will be updated without page reload -->
    <div id="result">
        <p>Data will appear here without reloading the page.</p>
    </div>

</body>
</html>

How This Script Works (AJAX Working Steps)

  1. The user clicks the "Click to Load Data" button, which triggers the loadData() function.
  2. A new XMLHttpRequest object (xhr) is created.
  3. The open() method specifies a GET request to ajax_info.txt with async = true (asynchronous).
  4. The send() method sends the request to the web server.
  5. When the server responds (readyState == 4 and status == 200), the onreadystatechange function is called.
  6. The response text from the server is displayed inside the <div id="result"> element without reloading the page.

Note: The file ajax_info.txt is a simple text file stored on the server that contains the data to be fetched and displayed.

Open this answer on its own page →

XML schema languages

2079 · 10 marks

What is the use of XML? Create a XML file with simple type and complex type elements. Write its equivalent DTD.[10]

Show solved answer

Use of XML, XML File with Simple/Complex Types, and Equivalent DTD

Uses of XML

XML (eXtensible Markup Language) is a markup language designed to store, transport, and structure data in a human-readable and machine-readable format. Its main uses are:

UseDescription
Data StorageStores data in a structured, self-describing format
Data TransportExchanges data between incompatible systems and platforms
Configuration FilesMany applications use XML for settings and configuration
Web ServicesSOAP-based web services use XML for request/response messages
Separation of Data from PresentationXML stores data; HTML/CSS handles display
Platform IndependenceWorks across different operating systems and programming languages
Document RepresentationUsed in formats like DOCX, SVG, and RSS feeds

XML File with Simple Type and Complex Type Elements

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>
    <book id="101">
        <title>Web Technology</title>
        <author>
            <firstname>John</firstname>
            <lastname>Smith</lastname>
        </author>
        <price>450.00</price>
        <year>2020</year>
    </book>
    <book id="102">
        <title>XML Fundamentals</title>
        <author>
            <firstname>Mary</firstname>
            <lastname>Jones</lastname>
        </author>
        <price>350.50</price>
        <year>2021</year>
    </book>
</library>

Explanation of Element Types

Simple Type Elements contain only text/data and no child elements:

  • <title>, <firstname>, <lastname>, <price>, <year>

Complex Type Elements contain other child elements or attributes:

  • <library> contains one or more <book> child elements
  • <book> contains child elements and has an attribute id
  • <author> contains <firstname> and <lastname> child elements

: "Simple type element is used only in the context of text" and "A complex type is a container for other element definitions, allowing us to specify which child elements an element can contain."


Equivalent DTD (Document Type Definition)

<!ELEMENT library (book+)>
<!ELEMENT book (title, author, price, year)>
<!ATTLIST book id CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (firstname, lastname)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT year (#PCDATA)>

Explanation of DTD Declarations

DTD DeclarationMeaning
<!ELEMENT library (book+)>library contains one or more book elements (+ means one or more)
<!ELEMENT book (title, author, price, year)>book is a complex type with four ordered child elements
<!ATTLIST book id CDATA #REQUIRED>book has a required attribute id of character data type
<!ELEMENT title (#PCDATA)>title is a simple type containing parsed character data (text only)
<!ELEMENT author (firstname, lastname)>author is a complex type with two child elements
<!ELEMENT firstname (#PCDATA)>firstname is a simple type containing text only
<!ELEMENT lastname (#PCDATA)>lastname is a simple type containing text only
<!ELEMENT price (#PCDATA)>price is a simple type containing text only
<!ELEMENT year (#PCDATA)>year is a simple type containing text only

: "In DTD, attributes are declared with an ATTLIST declaration" with syntax <!ATTLIST element-name attribute-name attribute-type attribute-value>.


Summary

  • XML provides a flexible, platform-independent way to structure and exchange data.
  • Simple type elements hold only text data (#PCDATA).
  • Complex type elements contain other child elements or attributes, acting as containers.
  • DTD defines the legal structure and rules for the XML document, ensuring data validity and consistency.
Open this answer on its own page →

2078 · 5 marks

What is DTD? Create a XML file and write its equivalent DTD. [5]

DTD (Document Type Definition) is a set of rules or declarations that defines the structure, legal elements, and attributes of an XML document. It acts as a blueprint that specifies: - What elements are allowed in the XML document - The order and nesting of elements - What attributes elements can...

Open this answer on its own page →

XML Namespace

2079 · 5 marks

What is XML Namespace? How is it used to avoid element name conflict in XML? Justify with an example. [5]

An XML Namespace is a mechanism used to avoid element name conflicts in XML documents by associating element and attribute names with a unique identifier (URI - Uniform Resource Identifier). When XML documents from different sources are combined, or when the same element name is used with differe...

Open this answer on its own page →

XSD Attributes

2076 · 5 marks

How XSD of a XML file is created? Illustrate with an example. [5]

XSD (XML Schema Definition) is a way to describe the structure and constraints of an XML document. It defines: - The elements and attributes that can appear in an XML document - The data types of elements and attributes - The number and order of child elements Note:, "XML schemas define datatypes...

Open this answer on its own page →