Extensible Markup Language (XML) Introduction and Advantages Advantages: Platform Independent: XML data can be easily transferred between different systems and applications. Self-describing: XML tags describe the data, making it human-readable and understandable. Data Storage and Transport: Excellent for storing and transporting data without being tied to specific display formats. Extensible: Users can define their own tags and document structure. Hierarchical Data: Well-suited for representing complex hierarchical data structures. Not a replacement for HTML: XML is for carrying data with a focus on what data is. HTML is for displaying data with a focus on how data looks. HTML has predefined tags; XML allows users to define custom tags. HTML vs. XML Feature HTML XML Purpose Display data, define web page structure Describe, store, and transport data Predefined Tags Yes No (user-defined) Case-Sensitivity No (mostly) Yes Error Handling Browser often corrects errors Strict, no errors allowed Closing Tags Optional for some tags Mandatory for all tags Syntax of XML Document Building Blocks: Element: Defined by a start tag, content, and an end tag (e.g., <book>Content</book> ). Attribute: Provides extra information about an element, specified within the start tag (e.g., <book id="123"> ). Prolog: Optional first line specifying XML version and encoding (e.g., <?xml version="1.0" encoding="UTF-8"?> ). Root Element: The topmost element that encloses all other elements. There can only be one root element. Comments: <!-- This is a comment --> . Well-formed XML: An XML document is well-formed if it adheres to XML syntax rules: Must have a root element. All elements must have a closing tag. Tags are case-sensitive. Elements must be properly nested. Attribute values must be quoted. Special characters must be escaped (e.g., < for < ). Example: <?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> XML Attributes Attributes provide metadata about an element, qualifying it rather than forming part of its content. They are defined as name-value pairs within the start tag of an element. Example: <product id="A101" category="electronics">Laptop</product> Here, id and category are attributes of the product element. Use elements for data, attributes for metadata. Practical Examples Grocery Store Inventory (3 entries) <?xml version="1.0" encoding="UTF-8"?> <grocery_store> <item> <item_code>G001</item_code> <name>Milk</name> <price>2.99</price> <expiry>2024-05-30</expiry> </item> <item> <item_code>G002</item_code> <name>Bread</name> <price>3.50</price> <expiry>2024-05-25</expiry> </item> <item> <item_code>G003</item_code> <name>Eggs</name> <price>4.10</price> <expiry>2024-06-10</expiry> </item> </grocery_store> Employee Contact Details <?xml version="1.0" encoding="UTF-8"?> <employees> <employee id="EMP001"> <name>Alice Smith</name> <department>HR</department> <phone>+1-555-123-4567</phone> <address>123 Main St, Anytown</address> </employee> <employee id="EMP002"> <name>Bob Johnson</name> <department>Engineering</department> <phone>+1-555-987-6543</phone> <address>456 Oak Ave, Somewhere</address> </employee> </employees> JSON (JavaScript Object Notation) Basics and Syntax Definition: A lightweight data-interchange format. It is human-readable and easy for machines to parse and generate. Based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999. JSON Object: An unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma). { "name": "John Doe", "age": 30, "isStudent": false } JSON Array: An ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma). [ "apple", "banana", "cherry" ] Created using HTML/JavaScript: // JavaScript Object const person = { name: "Jane", age: 25 }; // Convert JavaScript object to JSON string const jsonString = JSON.stringify(person); // jsonString will be: '{"name":"Jane","age":25}' // Parse JSON string back to JavaScript object const parsedObject = JSON.parse(jsonString); // parsedObject will be: { name: "Jane", age: 25 } JSON Data Types String: Sequence of zero or more Unicode characters, wrapped in double quotes. Example: "hello world" Number: Integer or floating-point. Example: 10 , 3.14 , -5 Boolean: true or false . Array: Ordered collection of values. Example: ["red", "green", "blue"] Object: Unordered collection of key-value pairs. Example: {"key": "value"} null: An empty value. Example: null JSON Schemas Purpose: JSON Schema is a powerful tool for validating the structure of JSON data. It defines the structure, content, and format of JSON documents. Helps ensure data consistency and integrity, useful for APIs and data exchange. Basic Syntax: A JSON Schema is itself a JSON document. { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Product", "description": "A product from ACME's catalog", "type": "object", "properties": { "productId": { "description": "The unique identifier for a product", "type": "integer" }, "productName": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "exclusiveMinimum": 0 } }, "required": ["productId", "productName", "price"] } JSON vs. XML Feature JSON XML Syntax Based on JavaScript objects Uses tags Readability Easier for humans to read Can be verbose Data Types Supports various types (string, number, boolean, array, object, null) All data is string by default Parsing Easier to parse by JavaScript Requires an XML parser (DOM, SAX) Schema JSON Schema for validation DTD, XML Schema (XSD) for validation Example { "name": "Alice" } <name>Alice</name> JavaScript XMLHttpRequest & Web APIs XMLHttpRequest (XHR) Definition: An API in web browsers that allows JavaScript to make HTTP requests to web servers without requiring a full page reload. This is crucial for AJAX (Asynchronous JavaScript and XML) development. Syntax and Usage: const xhr = new XMLHttpRequest(); xhr.open("GET", "https://api.example.com/data", true); // Method, URL, Async xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { const responseData = JSON.parse(xhr.responseText); console.log(responseData); } else if (xhr.readyState === 4 && xhr.status !== 200) { console.error("Error:", xhr.status, xhr.statusText); } }; xhr.send(); // Sends the request xhr.open(method, url, async) : Initializes a request. xhr.onreadystatechange : Event handler called when the readyState attribute changes. xhr.readyState : 0 : UNSENT 1 : OPENED 2 : HEADERS_RECEIVED 3 : LOADING 4 : DONE (request finished and response is ready) xhr.status : HTTP status code (e.g., 200 OK, 404 Not Found). xhr.responseText : The response body as a string. xhr.send() : Sends the request. Web APIs Definition: Application Programming Interfaces (APIs) provided by web servers to allow programmatic interaction with their services. They define a set of rules and protocols for how software components should interact. Role: Web APIs enable different applications to communicate and exchange data over the internet. Allow developers to access functionalities or data from existing services (e.g., Google Maps API, Twitter API). Facilitate the creation of rich, dynamic web applications by fetching data asynchronously. Often return data in JSON or XML format. JSON on the Server Side (PHP) Serialization and Deserialization JSON Serialization: The process of converting a data structure or object state into a format that can be stored or transmitted (e.g., a JSON string). json_encode() in PHP: Converts a PHP value (array or object) into a JSON string. Purpose: To prepare PHP data for sending to a client-side JavaScript application or storing it. Example: <?php $data = array("name" => "Alice", "age" => 30); $jsonString = json_encode($data); echo $jsonString; // Output: {"name":"Alice","age":30} ?> Deserializing JSON on the server-side: The process of converting a JSON string back into a programmatic data structure (e.g., a PHP array or object). json_decode() in PHP: Converts a JSON string into a PHP variable. Purpose: To parse JSON data received from a client-side application or an external API. The second parameter (boolean true ) makes it return an associative array; otherwise, it returns an object. Example: <?php $jsonString = '{"name":"Bob","age":25}'; $data = json_decode($jsonString, true); // true for associative array echo $data['name']; // Output: Bob ?> JSON.stringify() and JSON.parse() (JavaScript): JSON.stringify() : Converts a JavaScript value to a JSON string (client-side serialization). const obj = { id: 1, value: "test" }; const json = JSON.stringify(obj); // '{"id":1,"value":"test"}' JSON.parse() : Parses a JSON string, constructing the JavaScript value or object described by the string (client-side deserialization). const json = '{"id":1,"value":"test"}'; const obj = JSON.parse(json); // { id: 1, value: "test" } Processing JSON (JavaScript for loop structure) When JSON data (often an array of objects) is received and parsed in JavaScript, you can iterate over it using standard loop constructs. Example using for...of loop (modern JavaScript): const jsonData = [ { "name": "Alice", "score": 90 }, { "name": "Bob", "score": 85 }, { "name": "Charlie", "score": 92 } ]; for (const student of jsonData) { console.log(`Student: ${student.name}, Score: ${student.score}`); } // Output: // Student: Alice, Score: 90 // Student: Bob, Score: 85 // Student: Charlie, Score: 92 Example using traditional for loop: for (let i = 0; i < jsonData.length; i++) { console.log(`Student: ${jsonData[i].name}, Score: ${jsonData[i].score}`); } Example using forEach (for arrays): jsonData.forEach(student => { console.log(`Student: ${student.name}, Score: ${student.score}`); });