FSD Module 5 Notes
FSD Module 5 Notes
Ajax (Asynchronous JavaScript and XML) is not a standalone technology but rather a combination of existing
technologies to enable dynamic content updates on web pages without requiring a full page reload. The term
"overlaid function" means that Ajax utilizes and coordinates several different technologies to achieve its
functionality. These include:
JavaScript is the main engine for Ajax, enabling dynamic, asynchronous interactions on web pages.
JavaScript works with various technologies, including:
JavaScript Challenges
function outer() {
var result = 0;
for (var i = 0; i < 100; ++i) {
result += inner(i);
}
return result;
}
function inner(limit) {
var result = 0;
for (var i = 0; i < limit; ++i) {
result += i;
}
return result;
}
o Unexpected Behavior: Inconsistent scoping can lead to bugs.
2. Cross-Browser Inconsistencies:
o XMLHttpRequest: Different browsers handle XMLHttpRequest differently, leading to compatibility
issues.
o Testing: Developers must test across multiple browsers to ensure consistent behavior.
Simplifying Development: Libraries like jQuery provide consistent interfaces for handling
XMLHttpRequest, DOM manipulation, and more.
o Example: Using jQuery for an Ajax request:
$.ajax({
url: '/weather',
method: 'GET',
data: { city: 'New York' },
success: function(response) {
$('#weatherInfo').html(`
<h2>Weather in ${response.city}</h2>
<p>Temperature: ${response.temperature}°C</p>
<p>Condition: ${response.condition}</p>
`);
}
});
Misunderstood Language: Initially considered a "toy" language, JavaScript has matured and gained
recognition for its strengths.
Comparison to Python: Like Python, JavaScript is multiparadigm and supports dynamic, object-oriented
programming.
o Duck Typing: Both languages use duck typing, allowing flexible and interchangeable objects.
o Prototype-Based: JavaScript’s object-oriented model is based on prototypes, allowing dynamic
method and property attachment.
The XMLHttpRequest object is crucial for developing complex games using Ajax technologies, such as
massive multiplayer online role-playing games (MMORPGs).
It enables games that rely on network connectivity, such as "Ajax chess," which allows human players to
compete against each other over the network instead of playing against a computer engine.
This object is also fundamental for applications like Gmail, Google Maps, Bing Maps, and Facebook,
realizing Sun Microsystems' vision that "the network is the computer."
Using an XMLHttpRequest object typically involves creating or reusing the object, specifying a callback
event handler, opening the connection, sending data, and then having the callback handler retrieve and
act on the response once the network operation completes.
A basic XMLHttpRequest object includes essential methods and properties for handling these operations.
1. abort():
o Cancels any active request.
2. getAllResponseHeaders():
o Returns all HTTP response headers sent with the response.
3. getResponseHeader(headerName):
o Returns the requested header if available, or a browser-dependent false value if the header is not
defined.
4. open(method, URL, [asynchronous], [username], [password]):
o Initializes a request. The method can be GET, POST, HEAD, etc.
o The URL is the target URL for the request.
o asynchronous defaults to true. When set to false, it can lock up the visitor's browser.
o username and password are optional for HTTP authentication.
5. send(content):
o Sends the request with optional content, which can be a string or a reference to a document.
1. onreadystatechange:
o A property that holds a reference to the callback function to be executed when the state changes.
2. readyState:
o An integer representing the state of the request:
0: Uninitialized
1: Open
2: Sent
3: Receiving
4: Loaded
3. responseText:
o Contains the response data as a string when the request is complete.
4. responseXML:
o Contains the response data as an XML document.
5. status:
o The HTTP status code returned by the server (e.g., 200 for OK).
6. statusText:
o The HTTP status message returned by the server (e.g., "OK").
Example Usage
Different browsers have various implementations and levels of support for XMLHttpRequest, leading to
cross-browser compatibility issues.
Modern libraries like jQuery provide a consistent interface for Ajax requests, abstracting away these
differences.
5.4 HTML
HTML and XHTML are the foundational markup languages for the web. JavaScript and CSS were introduced
to complement HTML, although JavaScript has since gained recognition as a standalone language, used in
interpreters like SpiderMonkey and Rhino. HTML was the original web markup language, and other web
technologies have evolved around it. Even when HTML is re-implemented as XHTML, it retains its core purpose
while being more parser-friendly.
<HEADER>
<TITLE>The World Wide Web project</TITLE>
<NEXTID N="55">
</HEADER>
<BODY>
<H1>World Wide Web</H1>The WorldWideWeb (W3)
is a wide-area
<A NAME=0 HREF="WhatIs.html">
hypermedia</A> information retrieval
initiative aiming to give universal
access to a large universe of documents.<P>
Everything there is online about
W3 is linked directly or indirectly
to this document, including an
<A NAME=24 HREF="Summary.html">executive
summary</A> of the project,
<A NAME=29 HREF="Administration/Mailing/Overview.html">
Mailing lists</A> ,
<A NAME=30 HREF="Policy.html">Policy</A> , November's
<A NAME=34 HREF="News/9211.html">W3 news</A> ,
<A NAME=41 HREF="FAQ/List.html">Frequently Asked Questions
</A> .
<DL>
...
5.5 CSS
Cascading Style Sheets (CSS) introduced new ways to style web pages, but much of the presentation was
already possible before its arrival.
CSS didn't just add new styling capabilities; it brought better engineering to the process.
The core idea of CSS is to separate presentation from content, making it easier to create well-designed
web pages.
One of the benefits of CSS is the ability to rebrand websites easily. By changing images and a single
stylesheet, you can reskin a website without altering the HTML/XHTML markup.
For both Ajax and the broader web, the best practice is to use semantic and structural markup. Then, apply
styles through a stylesheet rather than inline, ensuring that elements with the appropriate class or ID have
the desired appearance.
Tables are still useful and not deprecated, but they should be used for displaying tabular data where using
table cells (<td>) and headers (<th>) makes sense. It is discouraged to use tables for positioning content
that is not actually tabular data.
5.6 JSON
5.7 iFrames
Iframes (short for inline frames) are HTML elements that allow you to embed another HTML document within the
current document. They are often used to display content from another source within a web page, such as
including a YouTube video, an advertisement, or content from another website.
Basic Syntax
Key Attributes
When developing a Django project, serving static content such as images, CSS, and JavaScript files is essential for
proper functionality and aesthetics. While a different approach is recommended for production, the following
steps outline how to set up static content for development purposes.
Steps:
First, create a directory named static within your Django project. This directory will hold all your static files.
mkdir static
Inside the static directory, create subdirectories for CSS, images, and JavaScript files:
2. Modify settings.py
Open your project's settings.py file and add the following configuration:
import os
DIRNAME = os.path.abspath(os.path.dirname(__file__))
At the end of the settings.py file, add the following snippet to serve static files when DEBUG is True:
if DEBUG:
from django.conf.urls.static import static
from django.conf import settings
This code dynamically adds URL patterns to serve static files during development.
Example settings.py
import os
# Media settings
MEDIA_ROOT = os.path.join(DIRNAME, 'static/')
MEDIA_URL = '/static/'
# Other settings...
For production, it is recommended to use a web server optimized for serving static content, such as Nginx or a
stripped-down Apache. Here’s a brief overview of how you can serve static files in production with Nginx:
2. Configure STATIC_ROOT
3. Nginx Configuration
Configure Nginx to serve the static files from the STATIC_ROOT directory. Here’s a sample Nginx
configuration:
server {
listen 80;
server_name your_domain.com;
location /static/ {
alias /path/to/your/project/staticfiles/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Example for Basic Ajax "Hello, World!" with JavaScript and jQuery
2) Configuring the request with the HTTP method and the URL:
jQuery Approach
With jQuery, the process is much simpler and more concise. Here's how you can achieve the same result using
jQuery:
2.Load content into the selected element from a server URL, optionally specifying a query string:
jQuery Wrapped Sets
A wrapped set in jQuery is an object that contains a set of DOM elements and provides a rich set of operations
you can perform on these elements
1.Chaining Operations:
jQuery operations return the same wrapped set, allowing methods to be chained together.
Example:
$("table.striped tr:even").addClass("even").hide("slow").delay(1000).show("slow");
2.Operation Examples:
Select even-numbered table rows from tables having the class striped.
$("table.striped tr:even")
Add the class even to these rows.
.addClass("even")
Slowly hide these rows.
.hide("slow")
Wait for 1000 milliseconds.
.delay(1000)
Slowly show these rows again.
.show("slow")
1. $.ajax()
2. $.ajaxSetup()
GET Example:
$.get("/resources/update", function(data) {
$("#result").html(data);
});
POST Example:
$("#result").html(data);
});
.load()
Loads data from the server and places the returned HTML into matched elements.
Example:
$("#messages").load("/sitewide-messages");
$("#messages").load("/user-messages", "username=jsmith");
performUserCustomizations(responseText);
});
Key Points
Convenience methods like $.get(), $.post(), and .load() are easier to use but lack detailed error handling.
Error handling: Prefer $.ajax() for robust error handling or use global error handlers with convenience
methods.
Context and closures: Useful for maintaining state in callbacks.
Chaining: Be cautious with chaining methods after .load() due to potential race conditions.
jQuery is a powerful and lightweight JavaScript library designed to simplify various web development tasks, such
as:
HTML Document Traversal and Manipulation: Allows for easy selection and manipulation of HTML
elements.
Event Handling: Simplifies attaching event listeners to elements, managing events like clicks, form
submissions, and more.
Animation: Enables creating dynamic and interactive effects.
Ajax Interactions: Simplifies making asynchronous HTTP requests for a seamless user experience.
Key Features and Benefits of jQuery
1) DOM Manipulation:
Ease of Use: Provides a straightforward API for selecting and manipulating elements within the Document
Object Model (DOM).
Flexibility: You can easily traverse the DOM tree, modify element attributes and content, and add or
remove elements from the page.
2) Event Handling:
Simplified Process: jQuery makes it simple to attach event listeners to HTML elements.
User Interactions: Handles various user interactions such as clicks, hovers, form submissions, and more.
To integrate jQuery UI's Autocomplete widget with a Django application, follow these steps:
1. Set Up Django View: Create a Django view that will serve the data for the autocomplete suggestions. This
view will return a JSON response.
3. Include jQuery and jQuery UI in Your Template: Make sure to include the jQuery and jQuery UI libraries in your
template. You can use CDN links for simplicity.
4. Testing the Autocomplete
Run your Django server and navigate to the page with the autocomplete input field. Start typing in the input field
to see the autocomplete suggestions in action.