Web Programming Pyq.html
Web Programming Pyq.html
formatting code
Here’s an HTML code that demonstrates various text formatting elements in HTML:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Text Formatting in HTML</title>
</head>
<body>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<p><tt>This is monospaced text using the <tt> tag.</tt></p>
</body>
</html>
This code demonstrates a variety of text formatting tags such as <b> , <i> , <u> ,
<mark> , <code> , <sub> , and others. You can run this code in a browser to see how
different HTML elements apply various styles to the text.
Here's an example of how you can create three web pages that allow navigation
between them using HTML and basic links.
Page 1 (home.html)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Home Page</title>
</head>
<body>
<h1>Welcome to the Home Page</h1>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<p>This is the first page of our website.</p>
<nav>
<ul>
<li><a href="about.html">Go to About Page</a></li>
<li><a href="contact.html">Go to Contact Page</a></li>
</ul>
</nav>
</body>
</html>
Page 2 (about.html)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>About Page</title>
</head>
<body>
<h1>About Us</h1>
<p>This is the second page of our website where we talk about ourselv
<nav>
<ul>
<li><a href="home.html">Go to Home Page</a></li>
<li><a href="contact.html">Go to Contact Page</a></li>
</ul>
</nav>
</body>
</html>
Page 3 (contact.html)
html
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Contact Page</title>
</head>
<body>
<h1>Contact Us</h1>
<p>This is the third page of our website where you can find our conta
<nav>
<ul>
<li><a href="home.html">Go to Home Page</a></li>
<li><a href="about.html">Go to About Page</a></li>
</ul>
</nav>
</body>
</html>
Explanation:
The three pages ( home.html , about.html , and contact.html ) are linked to
each other using the <a> tag with href attributes pointing to the respective pages.
The nav section on each page allows you to navigate between the pages by
clicking the links.
You can create these three HTML files, save them in the same folder, and open
home.html in a web browser. You will be able to navigate between the three pages
seamlessly.
1/2
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
CSS (Cascading Style Sheets) is used to style HTML elements and manage the visual
presentation of web pages. There are three main ways to apply CSS: inline, internal,
and external. This note focuses on internal and external CSS.
1. Internal CSS
Internal CSS refers to CSS that is embedded directly within an HTML document. The
styles are defined inside the <style> tag within the <head> section of the document.
Internal CSS is applied only to the specific HTML page in which it is written.
Syntax:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Internal CSS Example</title>
<style>
body {
background-color: lightblue;
}
h1 {
color: navy;
text-align: center;
}
p {
font-size: 20px;
}
</style>
</head>
<body>
<h1>This is an example of Internal CSS</h1>
<p>The styling is defined within the HTML document itself.</p>
</body>
</html>
Scope: The styles only apply to the HTML document where the <style> block is
placed.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Maintenance: If the design of multiple pages needs to be updated, each HTML
page would have to be modified individually, making it difficult to maintain for large
projects.
Use Case: Internal CSS is useful when a single page requires unique styling that
doesn't need to be applied to other pages.
Advantages:
Style definitions are only applied to the current page, ensuring isolation of styles.
Useful for small projects or when creating a unique style for a single page.
Disadvantages:
It makes the HTML file larger and harder to read if too much styling is embedded.
Poor scalability: It’s not practical for large websites with multiple pages.
2. External CSS
External CSS is a separate CSS file that contains all the style definitions for multiple
web pages. This file is linked to the HTML documents using the <link> tag in the
<head> section of the HTML file. The external CSS file is typically saved with a .css
extension.
Syntax:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External CSS Example</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<h1>This is an example of External CSS</h1>
<p>The styling is defined in a separate CSS file.</p>
</body>
</html>
css
body {
background-color: lightblue;
}
h1 {
color: navy;
text-align: center;
}
p {
font-size: 20px;
}
Scope: The styles are defined in a separate .css file and can be applied across
multiple HTML pages by linking the CSS file to each HTML page.
Maintenance: This method allows for easy updates, as any changes to the external
CSS file will automatically reflect across all the linked HTML pages.
Use Case: External CSS is commonly used in large web projects where multiple
pages share the same style or theme.
Advantages:
Efficiency: One CSS file can style multiple HTML documents, saving time and
making maintenance easier.
Separation of Concerns: Keeps the HTML structure separate from design, making
the code cleaner and easier to manage.
Faster Loading: Browsers cache external CSS files, leading to faster load times
when users navigate across different pages of the website.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Disadvantages:
Dependency: If the external CSS file is not loaded (e.g., network issues), the web
page may render without styling.
Location Defined within the <style> tag in an Defined in a separate .css file.
HTML file.
Reusability Limited to the HTML page in which it is Can be reused across multiple
embedded. HTML pages.
Maintenance Requires modifying each page for style Centralized maintenance; one file
updates. for all pages.
Performance Slower for large sites due to embedded Faster for large sites since CSS is
styles in each page. cached.
Conclusion:
Internal CSS is ideal for small-scale projects or when a single page needs special
styling.
External CSS is better suited for larger projects where multiple pages share the
same design elements, allowing for easier maintenance and faster page loading.
Both methods have their use cases depending on the scale of the project and specific
requirements.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Here's an HTML code that demonstrates how to insert different multimedia files (audio
and video) into a web page:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Multimedia on Web Page</title>
</head>
<body>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
</body>
</html>
Explanation:
1. Audio File:
Multiple sources are provided with <source> tags, allowing different formats
(MP3, OGG) for browser compatibility.
If the browser does not support the audio element, it will display a fallback
message.
2. Video File:
The controls attribute allows the user to control video playback (play/pause,
seek, volume).
Multiple source formats (MP4, OGG) are included for compatibility across
browsers.
The src attribute contains the URL of the video to be embedded, and the
allowfullscreen attribute enables full-screen viewing.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The <table> tag in HTML is used to create tables in a webpage, allowing for organized
data representation in rows and columns. The <table> tag works in conjunction with
several other tags like <tr> , <th> , and <td> to define the table structure.
html
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Example:
html
<table border="1">
2. cellpadding
Description: Adds padding inside each table cell, creating space between cell
content and the cell border.
Example:
html
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<table cellpadding="10">
3. cellspacing
Example:
html
<table cellspacing="5">
4. width
Example:
html
<table width="100%">
5. height
Example:
html
<table height="300">
Example:
html
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<table align="center">
Example:
html
<table bgcolor="#f2f2f2">
Example:
html
9. frame
Example:
html
<table frame="box">
10. rules
Example:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
html
<table rules="all">
<th> (Table Header): Defines a header cell. Text inside <th> is bold and centered
by default.
<thead> , <tbody> , and <tfoot> : Used to group table rows for better
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Example</title>
</head>
<body>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<td>Product A</td>
<td>$2000</td>
<td>$2500</td>
<td>$3000</td>
</tr>
<tr>
<td>Product B</td>
<td>$1500</td>
<td>$1800</td>
<td>$2200</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$3500</td>
<td>$4300</td>
<td>$5200</td>
</tr>
</tfoot>
</table>
</body>
</html>
This example demonstrates a table with the border, cellpadding, cellspacing, width,
align, bgcolor, frame, and rules attributes. Each attribute customizes the table's
appearance and structure, providing flexibility in how data is presented on a webpage.
Here's a complete HTML code for a student registration form, which includes various
form controls such as text inputs, radio buttons, checkboxes, dropdowns, text areas, and
a submit button.
html
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Student Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.registration-form {
background-color: #ffffff;
padding: 20px;
width: 400px;
border-radius: 8px;
box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
}
.registration-form h2 {
text-align: center;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.form-group input[type="text"],
.form-group input[type="email"],
.form-group input[type="number"],
.form-group input[type="date"],
.form-group select,
.form-group textarea {
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.form-group input[type="radio"],
.form-group input[type="checkbox"] {
margin-right: 10px;
}
.form-group textarea {
resize: vertical;
}
.submit-btn {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.submit-btn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="registration-form">
<h2>Student Registration Form</h2>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<input type="email" id="email" name="email" required>
</div>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<input type="checkbox" id="sports" name="hobbies" value="
<label for="sports">Sports</label>
<input type="checkbox" id="reading" name="hobbies" value=
<label for="reading">Reading</label>
<input type="checkbox" id="traveling" name="hobbies" valu
<label for="traveling">Traveling</label>
<input type="checkbox" id="music" name="hobbies" value="M
<label for="music">Music</label>
</div>
</body>
</html>
2. Email Input:
3. Number Input:
4. Date Input:
5. Radio Buttons:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<input type="radio"> for gender selection, allowing only one option to be
selected.
7. Checkboxes:
8. Textarea:
9. Submit Button:
Each form control is labeled for better accessibility, and the entire form is styled for a
clean and organized appearance. This registration form can be submitted to a server for
processing.
In JavaScript, you can create variables using the var , let , or const keywords,
followed by the variable name and an optional assignment of a value.
// Using var
var name = "John";
// Using let
let age = 25;
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Rules for Creating Variables in JavaScript
1. Variable Naming:
Variable names can contain letters, digits, underscores ( _ ), and dollar signs
( $ ).
They must begin with a letter, underscore ( _ ), or dollar sign ( $ ). They cannot
start with a digit.
2. Case Sensitivity:
Variable names are case-sensitive. For example, age and Age would be
treated as two different variables.
3. Reserved Words:
4. Descriptive Names:
5. No Special Characters:
javascript
Invalid:
javascript
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
const function = 10; // Reserved keyword
2/2
javascript
function isPrime(number) {
if (number <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
return false; // Found a factor, so it is not prime
}
}
return true; // No factors found, so it is prime
}
// Example usage:
const number = parseInt(prompt("Enter a number:"));
if (isPrime(number)) {
console.log(number + " is a prime number.");
} else {
console.log(number + " is not a prime number.");
}
Explanation
1. Edge Case Check:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The for loop starts from 2 and goes up to the square root of the number
( Math.sqrt(number) ). This is because if number has a factor greater than its
square root, it must also have a corresponding factor smaller than its square
root, so we only need to check up to the square root.
4. Return Result:
XML (eXtensible Markup Language) is designed to store and transport data, providing a
flexible way to create and share structured data. Here are some of the key features of
XML:
1. Self-Descriptive Structure
XML documents contain both data and markup to describe the data, making them
self-descriptive and readable. Tags are custom-defined, providing meaningful labels
to the data (e.g., <name> , <age> ).
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
XML allows validation through DTD (Document Type Definition) and XML Schema
(XSD). These standards ensure that XML documents follow specified structures and
data types, improving data integrity.
5. Extensibility
XML provides flexibility by allowing users to define their own tags, making it
adaptable to a wide range of data structures and applications.
6. Unicode Support
XML supports Unicode, making it capable of handling text in any language, which is
essential for applications that need to support global data exchange.
9. Data Interchange
XML is commonly used as a data interchange format due to its structured nature. It
is compatible with various protocols, APIs, and file types, facilitating data exchange
between web services, databases, and applications.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
write a note on DTD
A Document Type Definition (DTD) defines the structure and the legal elements and
attributes of an XML document. It acts as a blueprint, specifying the rules the XML
document must follow, including what elements can be included, the attributes each
element can have, and the nesting structure of elements. DTDs play an essential role in
validating XML documents to ensure they are structured consistently and conform to
specified requirements.
2. Attribute Declarations:
3. Entity Declarations:
4. Notations:
Types of DTD
1. Internal DTD:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Defined within the XML document itself, usually within the <!DOCTYPE>
declaration.
Example:
xml
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
2. External DTD:
Stored as a separate file and linked to the XML document. This enables multiple
XML documents to share the same DTD, promoting reusability.
Example:
xml
Limitations of DTD
1. Limited Data Types: Unlike XML Schema, DTD only supports a few data types,
such as ID and CDATA .
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
3. Different Syntax from XML: DTDs use a different syntax, which can make them
harder to learn and read compared to other XML schema languages, like XML
Schema Definition (XSD).
Example of DTD
Here's an example of a DTD file ( bookstore.dtd ) for a bookstore XML document:
xml
xml
In this example, the XML document is validated against the bookstore.dtd file,
ensuring it meets all structural requirements specified by the DTD.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
create an XML file for student which includes element as roll
on name contact no
Here's an XML file for a student record, including elements for roll_no , name , and
contact_no . Each student record can be placed inside a root element like
<students> , with each student represented by a <student> element containing their
details.
<student>
<roll_no>102</roll_no>
<name>Jane Smith</name>
<contact_no>0987654321</contact_no>
</student>
<student>
<roll_no>103</roll_no>
<name>Michael Johnson</name>
<contact_no>1122334455</contact_no>
</student>
</students>
Explanation
Root Element: <students> is the root element that contains all student records.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<roll_no> : Represents the student's roll number.
This XML structure provides a clear and organized way to store multiple student records
in a standardized format.
Here's a JavaScript code snippet that validates both a range of numerical values and an
email string format.
Code Explanation:
1. Range Validation: Checks if a number falls within a specified range (e.g., 1 to 100).
JavaScript Code
javascript
function validateEmail(email) {
// Regular expression for validating email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailRegex.test(email)) {
return true; // Email is valid
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
} else {
console.log("Invalid email format.");
return false;
}
}
// Example Usage:
const numberToCheck = 25;
const minRange = 1;
const maxRange = 100;
const emailToCheck = "example@example.com";
// Validate range
if (validateRange(numberToCheck, minRange, maxRange)) {
console.log("The number is within the specified range.");
} else {
console.log("The number is out of range.");
}
// Validate email
if (validateEmail(emailToCheck)) {
console.log("The email format is valid.");
} else {
console.log("The email format is invalid.");
}
Explanation
Range Validation:
Returns true if within range; otherwise, prints an error message and returns
false .
Email Validation:
Returns true if the email matches the regex; otherwise, prints an error
message and returns false .
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Example Output
plaintext
AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to
update data dynamically without reloading the entire page. This enhances user
experience by creating faster, more interactive, and seamless applications.
1. Event Triggered:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The server receives the request, processes it, and prepares the response. This
could involve querying a database, performing calculations, or simply preparing
data to be sent back to the client.
The server sends the response back to the client in a specified format, often
JSON, XML, HTML, or plain text.
The JavaScript code updates only the necessary parts of the webpage with the
received data, such as updating a portion of text, adding new content, or
refreshing part of the page without reloading the entire page.
javascript
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
}
};
AJAX requests are typically asynchronous, meaning the browser doesn’t wait
for the server’s response to continue executing other code. This enables
smoother interactions on the page, as users don’t experience delays while
waiting for data.
3. Cross-Origin Requests:
4. Error Handling:
Proper error handling is important to provide fallback options if the server fails
to respond or returns an error, enhancing the reliability of AJAX applications.
Advantages of AJAX
Faster Interactions: AJAX allows only parts of the page to update, which reduces
the load time.
Reduced Server Load: Since AJAX only requests necessary data, it reduces the
overall data transferred, lowering server load.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The fetch API is a modern alternative to XMLHttpRequest , providing a simpler and
more flexible way to handle AJAX calls.
javascript
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
document.getElementById("content").innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
})
.catch(error => console.error("Error:", error));
Summary
AJAX is a powerful tool for creating interactive and responsive web applications by
enabling asynchronous communication between the client and server, improving user
experience by updating only parts of the page as needed.
Cookies are small pieces of data stored on a user's computer by a web browser while
browsing a website. They are used to retain user information, personalize the user
experience, track behavior, and manage sessions. Cookies play an essential role in
modern web applications and enable a wide range of functionalities.
When a user visits a website, the server sends a Set-Cookie header with
specific data to the browser.
The browser then stores this cookie data locally and sends it back to the server
with every request to the same domain, enabling stateful interactions.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
2. Structure of a Cookie:
Example:
css
With each request to the server, the browser includes all cookies that match the
current domain and path. This allows the server to identify users, track
sessions, and customize content.
Types of Cookies
1. Session Cookies:
These cookies are temporary and are deleted once the browser is closed.
2. Persistent Cookies:
Persistent cookies have an expiration date set in the future and remain on the
user’s device until they expire or are manually deleted.
Useful for remembering user preferences, login details, or tracking over time.
3. First-Party Cookies:
Created and used by the website the user is directly interacting with.
4. Third-Party Cookies:
Created by domains other than the website the user is visiting, often through
embedded content such as ads or social media widgets.
Primarily used for tracking and advertising, but these cookies have raised
privacy concerns and are increasingly restricted by modern browsers.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Key Attributes of Cookies
1. Expires / Max-Age:
Determines how long the cookie will persist. If neither Expires nor Max-Age
is specified, the cookie becomes a session cookie and is deleted when the
browser closes.
The Domain attribute specifies which domains can access the cookie. By
default, cookies are only available to the domain that set them.
Path defines the specific directory or page on the server that can access the
cookie. Setting the path to / makes the cookie available site-wide.
3. Secure:
Indicates that the cookie should only be sent over HTTPS connections,
enhancing security by preventing the cookie from being transmitted over
insecure HTTP.
4. HttpOnly:
When enabled, this attribute prevents JavaScript from accessing the cookie,
making it more secure against Cross-Site Scripting (XSS) attacks.
5. SameSite:
Strict : Cookies only sent when the domain in the URL matches the
domain of the cookie.
Lax : Cookies sent with some cross-site requests, like following a link.
Setting a Cookie
javascript
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
document.cookie = "username=JohnDoe; expires=Wed, 21 Oct 2024 07:28:00 GM
Reading Cookies
JavaScript can read cookies using document.cookie , which returns all cookies in a
single string:
javascript
Deleting Cookies
javascript
Advantages of Cookies
1. Maintaining State: Cookies allow the server to remember state across requests,
making features like sessions, login states, and user preferences possible.
3. Tracking and Analytics: Cookies allow websites to track user activity, providing
data for analytics and user behavior insights.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
3. Privacy Issues: Third-party cookies raise privacy concerns as they enable tracking
of users across different sites. Regulatory measures, such as the GDPR and CCPA,
have addressed these concerns.
javascript
// Example usage
setCookie("theme", "dark", 7); // Set theme preference to "dark" for 7 da
console.log(getCookie("theme")); // Output: "dark"
deleteCookie("theme"); // Deletes the "theme" cookie
Summary
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Cookies are essential for enabling stateful interactions on the web, allowing websites to
remember user information, manage sessions, and track user behavior. However, they
come with security and privacy implications, making it important for developers to use
cookies responsibly by leveraging attributes like HttpOnly , Secure , and SameSite .
In PHP, arrays are used to store multiple values in a single variable. PHP offers several
ways to create arrays, including indexed, associative, and multidimensional arrays.
1. Indexed Arrays
An indexed array stores values with numeric indices (starting from 0).
Syntax
php
php
Example
php
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Output: Apple
?>
2. Associative Arrays
An associative array uses named keys (strings) to access values, making it useful for
storing related data in a key-value format.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Syntax
php
php
Example
php
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");
echo $person["name"]; // Output: John
?>
3. Multidimensional Arrays
A multidimensional array contains one or more arrays inside it, allowing you to store
complex data structures.
Example
php
<?php
$students = [
["name" => "Alice", "age" => 20, "major" => "Math"],
["name" => "Bob", "age" => 22, "major" => "Science"],
["name" => "Carol", "age" => 21, "major" => "Literature"]
];
echo $students[0]["name"]; // Output: Alice
?>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Example: Using foreach with Associative Array
php
<?php
$person = ["name" => "John", "age" => 30, "city" => "New York"];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
// Output:
// name: John
// age: 30
// city: New York
?>
Summary
PHP arrays are flexible and can hold different types of data with both numeric and
associative keys. They can also be nested to create multidimensional arrays, making
PHP arrays suitable for complex data management.
Here are examples of common PHP string functions that can manipulate and handle
strings effectively.
php
<?php
// Sample String
$text = "Hello, World!";
$text2 = "PHP is fun!";
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
// 3. strrev() - Reverse a string
echo "Reversed text: " . strrev($text) . "\n"; // Output: !dlroW ,olleH
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
?>
8. substr() : Returns a substring from the specified start position and length.
12. trim() : Removes whitespace from the beginning and end of the string.
These examples demonstrate how PHP's string functions can be used to manipulate and
handle strings effectively in different scenarios.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
jQuery Events
Events in jQuery are actions that occur due to user interactions or browser actions.
jQuery simplifies event handling with methods to bind events to elements, allowing you
to write code that responds to user actions quickly and efficiently.
1. Mouse Events
javascript
$("#button").click(function(){
alert("Button clicked!");
});
2. Keyboard Events
javascript
$(document).keydown(function(event){
console.log("Key pressed: " + event.key);
});
3. Form Events
change() : Triggers when the value of an element changes (e.g., input, select).
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
blur() : Triggers when an element loses focus.
javascript
$("input").focus(function(){
$(this).css("background-color", "yellow");
});
4. Window/Document Events
javascript
$(window).resize(function(){
console.log("Window resized.");
});
Event Delegation
Using on() for dynamic elements is a common jQuery approach, allowing you to attach
events to elements that may not yet exist when the script runs.
javascript
jQuery Effects
jQuery offers multiple methods to add visual effects and animations to web elements,
making UI interactions smoother and more engaging.
Basic Effects
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
javascript
$("#element").hide();
$("#element").show();
2. toggle()
javascript
$("#toggleButton").click(function(){
$("#element").toggle();
});
javascript
$("#fadeButton").click(function(){
$("#element").fadeIn("slow");
});
javascript
$("#fadeToButton").click(function(){
$("#element").fadeTo("slow", 0.5); // fades to 50% opacity
});
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
javascript
$("#slideUpButton").click(function(){
$("#element").slideUp("fast");
});
6. slideToggle()
javascript
$("#toggleSlideButton").click(function(){
$("#element").slideToggle("slow");
});
Custom Animations
javascript
$("#animateButton").click(function(){
$("#element").animate({
width: "50%",
opacity: 0.8
}, "slow");
});
Chaining Effects
You can chain multiple jQuery effects and events in one line for a streamlined approach.
javascript
$("#chainButton").click(function(){
$("#element").slideUp(1000).slideDown(1000).fadeOut(1000).fadeIn(1000)
});
Summary
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Events: jQuery simplifies handling user and browser events like clicks, keypresses,
form submissions, and window actions.
Effects: jQuery provides numerous effects like show/hide, fade, slide, and custom
animations to enhance the user interface.
javascript
$.ajax({
url: "server/data",
type: "GET",
success: function(response) {
// This function runs once the data is returned
console.log("Data received:", response);
},
error: function(error) {
console.log("Error:", error);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
}
});
In this example, success is a callback function that will execute only after the server
sends a response. Meanwhile, other scripts and page interactions continue without
waiting for the AJAX call to complete.
2. Efficient Data Loading: Only specific parts of the page need to be updated.
Asynchronous: JavaScript continues executing other code while the AJAX request
processes in the background.
In modern web development, asynchronous requests are almost always preferred due
to their efficiency and smoother user experience.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
1. Positioning Context: An absolutely positioned element is placed relative to its
nearest positioned ancestor (i.e., an ancestor element with a position of relative ,
absolute , or fixed ). If no such ancestor exists, it positions itself relative to the
document body.
2. Values for top , right , bottom , and left : These properties specify the
distance from the respective sides of the containing element.
Syntax
css
#example {
position: absolute;
top: 50px;
left: 100px;
}
In this example, the element with ID example will be placed 50px from the top and
100px from the left of its containing element or the document body.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Absolute Positioning Example</title>
<style>
.container {
position: relative;
width: 300px;
height: 200px;
background-color: lightblue;
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
.box {
position: absolute;
top: 20px;
left: 30px;
width: 100px;
height: 100px;
background-color: coral;
}
</style>
</head>
<body>
<div class="container">
<p>This is a container element.</p>
<div class="box">Absolutely Positioned Box</div>
</div>
</body>
</html>
Explanation
Container: The .container element is given position: relative; , meaning it
will serve as a positioning reference for its child elements with absolute positioning.
Box: The .box element is given position: absolute; , top: 20px; , and left:
30px; . This means that the .box is positioned 20px from the top and 30px from
the left within the .container .
Output
In this example:
The "Absolutely Positioned Box" will appear inside the container, offset by 20px from
the top and 30px from the left.
If no position were set on .container , .box would position itself relative to the
document body instead.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Here's an example HTML code that demonstrates image mapping, which allows
specific areas within an image to act as clickable links, leading to different destinations.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Image Mapping Example</title>
</head>
<body>
</body>
</html>
Explanation
1. Image with usemap Attribute:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The img tag has the attribute usemap="#sample-map" , which links it to the
<map> element by name.
Each <area> element has an href attribute to specify the link and a
target="_blank" attribute to open the link in a new tab.
Result
The image will display clickable areas that link to Google, Bing, and Yahoo.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element attribute="value">Text Content</element>
<parent>
<child>Child Content</child>
<child attribute="value" />
</parent>
<selfClosingElement />
</root>
The XML declaration is optional but recommended. It specifies the XML version
and character encoding.
Every XML document must have a single root element that contains all other
elements.
This is the top-most element, and it wraps the entire content of the XML
document.
Elements are the primary building blocks in XML, used to represent data.
4. Attributes ( attribute="value" )
They are defined within the start tag of an element in name="value" format.
Attributes are used sparingly in XML as elements are preferred for hierarchical
data.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
5. Text Content
Elements can contain text between their start and end tags, representing data
values.
Text content should not contain special characters (like < , > , & ), unless
escaped (e.g., < for < ).
6. Child Elements
Elements that do not contain any child elements or text content can be self-
closed.
Self-closing syntax ( <element /> ) is often used for elements that act as
placeholders or metadata.
Explanation of Example
Root Element: <library> is the root element that contains all other elements.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Child Elements: <book> elements are child elements within <library> ,
representing individual books.
2. Elements must have matching start and end tags and be properly nested.
3. Element names are case-sensitive and cannot start with numbers or punctuation,
except for underscores.
This structured format makes XML useful for representing complex data hierarchies,
enabling data interchange across different systems and platforms.
Here’s a simple JavaScript code to find the length of an entered string. This code takes
user input, finds the length of the string, and then displays the result.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>String Length Finder</title>
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
</head>
<body>
<p id="result"></p>
<script>
function findStringLength() {
// Get the entered string value
const inputString = document.getElementById("inputString").va
</body>
</html>
Explanation
1. HTML Structure:
There’s an input field ( <input type="text"> ) where the user can enter the
string.
A <p> element with the id result displays the length of the entered string.
The function retrieves the entered string from the input field using
document.getElementById("inputString").value .
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
The result is then displayed in the <p> element by updating its innerHTML .
This code will display the length of the entered string below the input field.
The XMLHttpRequest object in JavaScript is used to interact with servers and send
HTTP requests asynchronously. It allows you to retrieve data from a server without
refreshing the entire web page, which is essential for creating dynamic and interactive
web applications.
1. Creating an Instance:
You can create an instance of the XMLHttpRequest object using the following
syntax:
javascript
2. Opening a Request:
Use the open method to initialize a request. You need to specify the request
method (GET, POST, etc.) and the URL.
javascript
3. Setting Up Callbacks:
You can define a callback function to handle the server response by setting the
onreadystatechange event. This function is called whenever the readyState
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
javascript
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // Request is complete
if (xhr.status === 200) { // Successful response
console.log("Response:", xhr.responseText);
} else {
console.error("Error:", xhr.status);
}
}
};
javascript
xhr.send();
Complete Example
Here’s a complete example that demonstrates how to use the XMLHttpRequest object
to fetch data from an API and display it in the console:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>XMLHttpRequest Example</title>
</head>
<body>
<script>
function fetchData() {
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
var xhr = new XMLHttpRequest(); // Create XMLHttpRequest obje
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts",
</body>
</html>
The response is parsed as JSON and displayed in the <pre> tag and console.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Key Points
The XMLHttpRequest object is powerful for making HTTP requests.
Always check the readyState and status to handle the response appropriately.
Consider using modern alternatives like the Fetch API for simpler syntax and better
functionality in modern browsers.
To retrieve cookies in PHP, you can access the $_COOKIE superglobal array, which
contains all the cookies sent by the client in the HTTP request. Each cookie can be
accessed using its name as the key.
php
<?php
// Set a cookie for demonstration purposes (this is usually done in anoth
setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // Expires
setcookie("user_role", "admin", time() + (86400 * 30), "/"); // Expires i
// Retrieve cookies
if(isset($_COOKIE["username"])) {
$username = $_COOKIE["username"];
} else {
$username = "Guest"; // Default value if cookie doesn't exist
}
if(isset($_COOKIE["user_role"])) {
$userRole = $_COOKIE["user_role"];
} else {
$userRole = "not assigned"; // Default value if cookie doesn't exist
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
echo "<h2>Cookie Values:</h2>";
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "User Role: " . htmlspecialchars($userRole) . "<br>";
?>
The first parameter is the cookie name, the second is the value, the third is the
expiration time (in seconds), and the fourth parameter specifies the path on the
server.
2. Retrieving Cookies:
The code checks if the cookies username and user_role are set using
isset() .
Important Notes
Cookies must be sent before any HTML output is generated. If you need to set
cookies, ensure it occurs before any <html> or output.
Cookies have a size limit (about 4 KB) and can have different expiration times.
To see the effect of setting cookies, you may need to refresh the page after the initial
request, as cookies are sent in subsequent requests.
Usage
1. Save the above code in a .php file on your server.
2. Access the file via a web browser. The page will set the cookies and then display the
retrieved values. Refreshing the page should still show the cookie values since they
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
persist for 30 days as per the example.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF