0% found this document useful (0 votes)
11 views39 pages

Module 5

Module 5 of Fullstack Development focuses on integrating jQuery and AJAX in Django to create dynamic web applications. It covers key concepts such as AJAX techniques, JavaScript, and the XMLHttpRequest object, emphasizing the advantages of asynchronous communication for user experience. The module aims to equip learners with the skills to build responsive applications by leveraging jQuery and AJAX functionalities within Django frameworks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

Module 5

Module 5 of Fullstack Development focuses on integrating jQuery and AJAX in Django to create dynamic web applications. It covers key concepts such as AJAX techniques, JavaScript, and the XMLHttpRequest object, emphasizing the advantages of asynchronous communication for user experience. The module aims to equip learners with the skills to build responsive applications by leveraging jQuery and AJAX functionalities within Django frameworks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

FULLSTACK DEVELOPMENT (21CS62)

MODULE – 5
JQUERY AND AJAX INTEGRATION IN DJANGO

• jQuery and AJAX Integration in Django


• Ajax Solution
• Java Script
• XHTMLHttpRequest and Response
• HTML
• CSS
• JSON
• iFrames
• Settings of Java Script in Django
• jQuery and Basic AJAX
• jQuery AJAX Facilities
• Using jQuery UI Autocomplete in Django.

Objectives
Design and implement Django apps containing dynamic pages with SQL databases..

Outcomes
Perform jQuery based AJAX integration to Django Apps to build responsive full stack web
applications.

SHILPA B, DEPT. OF ISE, CEC 1


FULLSTACK DEVELOPMENT (21CS62)

SESSION – 33
1. JQUERY AND AJAX INTEGRATION IN DJANGO
Django is a leading Python web framework known for its ease of use and powerful capabilities.
It enables developers to create robust web applications quickly. On the client side, jQuery, a
lightweight JavaScript library, simplifies HTML document traversing, event handling, and
Ajax interactions, making it an excellent choice for enhancing web applications with dynamic
content.
Ajax: A Technique, Not a Technology
Ajax stands for Asynchronous JavaScript and XML. It's not a single technology but a set of
techniques used together to create asynchronous web applications. This means that parts of a
web page can be updated without reloading the entire page, leading to a smoother and more
responsive user experience. Ajax combines several technologies:
• HTML and CSS for presenting information.
• JavaScript for dynamic content and interactivity.
• DOM (Document Object Model) for accessing and manipulating HTML.
• XMLHttpRequest for asynchronous communication with the server.
• JSON (JavaScript Object Notation) or XML for data interchange.
jQuery: The JavaScript Library
jQuery simplifies many aspects of JavaScript programming. It abstracts complex tasks, making
it easier to achieve powerful results with less code. Some of its key features include:
• DOM Manipulation: jQuery allows for easy selection and manipulation of HTML
elements.
• Event Handling: Simplified handling of events like clicks, hovers, and form
submissions.
• Ajax: jQuery provides a simple interface for making asynchronous requests to the
server, which is essential for creating dynamic web applications.
Django: The Python Web Framework
Django follows the "batteries-included" philosophy, providing a lot of built-in features out of
the box. It emphasizes reusability, rapid development, and the "don't repeat yourself" (DRY)
principle. Key components include:
• Models: Define the data structure.
• Views: Handle the business logic and interact with models.

SHILPA B, DEPT. OF ISE, CEC 2


FULLSTACK DEVELOPMENT (21CS62)

• Templates: Define how the data is presented.


• Forms: Handle user input and validation.
• Admin Interface: A powerful interface for managing application data.
Kickstarting Django: "Hello, World!"
To get started with Django, you typically create a project and an application within that project.
A minimal Django project includes setting up the necessary configurations, creating models to
define data structures, and setting up views and templates to handle and present data. A basic
"Hello, World!" example helps familiarize you with the Django framework, setting the stage
for more complex applications.
Django Templating Engine
Django's templating engine allows you to define the presentation layer. It enables you to create
dynamic HTML by embedding Django template language (DTL) within HTML files. This
separation of concerns makes it easier to manage and maintain your code, ensuring that the
presentation logic is kept separate from business logic.
Serving Static Content in Django
Static files include images, CSS, JavaScript, and other files that don’t change frequently.
Django provides a straightforward way to serve static content. During development, the
django.contrib.staticfiles app helps manage static files, while for production, you need to
configure a web server like Nginx or Apache to serve these files efficiently.
Laying the Foundation
The initial chapter sets the groundwork for integrating Django and Ajax. By understanding the
basic components of Django, how to set up a project, and how to serve static content, you can
start building dynamic web applications. The focus is on creating a strong foundation to explore
more advanced features and interactions between Django and Ajax in subsequent chapters.

Questions
• What are the different technologies in Ajax?
• What are the key components in Django- Python Web Framework?

SHILPA B, DEPT. OF ISE, CEC 3


FULLSTACK DEVELOPMENT (21CS62)

Session - 34
2. AJAX SOLUTION
Ajax stands for "Asynchronous JavaScript and XML." It is a technique used to create fast and
dynamic web pages by enabling asynchronous communication between the client-side and
server-side without requiring a full page reload.
Ajax vs. Traditional Page Updates
Traditional Method (Web 1.0): Whole page updates, where clicking a link or submitting a
form results in the entire page being replaced by a new page loaded from the server.
Ajax (Web 2.0): Partial page updates, where only a portion of the page is updated with new
data from the server, enhancing user experience by making the interaction more seamless and
responsive.
Use Cases
• E-commerce Sites: An e-commerce site can use Ajax to enhance user experience by
providing quick updates and feedback without reloading the entire page.
• For instance, updating a shopping cart, filtering products, or providing instant search
results.
• Community Contributions: Web 2.0 sites often use Ajax to facilitate user interactions and
contributions, such as comments, ratings, and real-time updates.
Key Points
• Efficiency: Ajax improves the efficiency of web applications by reducing server load and
bandwidth usage since only necessary data is sent and received.
• User Experience: By avoiding full page reloads, Ajax creates a smoother and more
interactive experience for users.
• Flexibility: Developers can use Ajax to implement dynamic features that respond to user
input in real-time, enhancing the functionality of web applications

3. JAVA SCRIPT
JavaScript holds a central place in the world of Ajax development. While other scripting
languages like VBScript can be used in Internet Explorer, JavaScript is the predominant
language for Ajax, working seamlessly with technologies like XMLHttpRequest, HTML,
XHTML, HTML5, the DOM, CSS, XML, and JSON.
JavaScript’s Dual Nature

SHILPA B, DEPT. OF ISE, CEC 4


FULLSTACK DEVELOPMENT (21CS62)

Addressing a group of Django developers or Python enthusiasts, one might say, "I share your
enthusiasm." For JavaScript developers, however, it's more fitting to say, "I feel your pain."
JavaScript is a language that has been both celebrated and criticized. It is often described as a
blend of excellence and flaws, making it both a remarkable and challenging language.
Challenges in JavaScript
1. Language Decisions: JavaScript’s design decisions can be perplexing. For instance, it was
intended to resemble Java but be simpler for non-programmers, a choice similar to the
rationale behind SQL and COBOL. JavaScript’s variable scope management can be
problematic. In a scenario where variables are not explicitly declared local within functions
using var, functions can inadvertently overwrite each other’s variable values.
javascript
Copy code
function outer() {
result = 0;
for(i = 0; i < 100; ++i) {
result += inner(i);
}
return result;
}
function inner(limit) {
result = 0;
for(i = 0; i < limit; ++i) {
result += i;
}
return result;
}
In this example, the i variable in inner function can interfere with i in outer function,
causing unexpected results.
2. Inconsistent Implementation: JavaScript suffers from inconsistent implementations
across different browsers. This leads to the well-known issue of "Write once, debug
everywhere." The most critical object for Ajax, XMLHttpRequest, often requires different
handling across browsers, leading to compatibility issues. Cross-browser testing becomes
essential to ensure uniform behavior.

SHILPA B, DEPT. OF ISE, CEC 5


FULLSTACK DEVELOPMENT (21CS62)

Mitigating Pain with Libraries


Using a robust JavaScript library like jQuery can alleviate much of this pain. Libraries abstract
away the inconsistencies, providing a consistent API for tasks like creating XMLHttpRequest
objects. This allows developers to write cleaner, more maintainable code without worrying
about browser-specific quirks.
Strengths of JavaScript
Despite its flaws, JavaScript possesses deep strengths that make it a powerful language. Its
dynamic nature and support for multiple programming paradigms, including object-oriented
programming, make it versatile. Unlike Java, where class definitions are rigid, JavaScript
allows dynamic modification of objects. Methods and properties can be added or removed at
runtime.
Duck Typing
JavaScript, like Python, is a duck-typed language. This means that an object’s suitability for
use is determined by the presence of certain methods and properties rather than its inheritance
from a specific class. This flexibility allows for the creation of drop-in replacements for objects
without modifying existing code, provided they adhere to the expected interface.
JavaScript’s Evolution
The perception of JavaScript is evolving. More developers are recognizing its capabilities
beyond its initial design flaws and the misleading "Java" branding. Good programmers grow
by learning new languages, and JavaScript, with its robust feature set, offers much to explore.
Selective Use of JavaScript with jQuery
In this book, we will make selective use of JavaScript, primarily through the jQuery library.
jQuery simplifies many common tasks in JavaScript development, making it analogous to the
power and ease of use that Python brings to programming. It provides an efficient way to
manipulate the DOM, handle events, and perform Ajax requests, reducing the complexity and
increasing productivity.

Questions
• What is the full form of Ajax?
• What are the use cases of Ajax?
• What is java script?

SHILPA B, DEPT. OF ISE, CEC 6


FULLSTACK DEVELOPMENT (21CS62)

Session - 35
4. XHTMLHTTPREQUEST AND RESPONSE
The XMLHttpRequest object is foundational for modern web applications, making real-time,
network-driven interactions possible. The XMLHttpRequest object allows web applications to
communicate with servers asynchronously, fetching data or sending updates without needing
to reload the entire page. Applications like Gmail, Google Maps, Bing Maps, and Facebook
rely on XMLHttpRequest to provide seamless, dynamic user experiences.
Basic Usage Pattern
• Creation or Reuse:Prefer reusing existing XMLHttpRequest objects rather than creating
and discarding many instances to optimize performance.
• Specify a Callback Handler:Assign a function to handle the response from the server once
the request is complete.
• Open the Connection:Initialize the request by specifying the HTTP method (e.g., GET,
POST) and the URL to which the request should be sent.
• Send the Data:Send the request to the server.
• Handle the Response:When the server responds, the callback handler processes the
response, updating the UI or taking other appropriate actions.
Methods
1. XMLHttpRequest.abort()
Use this method to abort the current request if you no longer need its response or need to free
up resources. xhr.abort();
2. XMLHttpRequest.getAllResponseHeaders()
Use this method to retrieve all headers from the server's response
var headers = xhr.getAllResponseHeaders();
3. XMLHttpRequest.getResponseHeader(headerName)
Use this method to get the value of a specific response header.
var contentType = xhr.getResponseHeader('Content-Type');
4. XMLHttpRequest.open()
It takes up to five arguments:
• method: The HTTP method to use (e.g., GET, POST, HEAD).
• URL: The URL to send the request to.

SHILPA B, DEPT. OF ISE, CEC 7


FULLSTACK DEVELOPMENT (21CS62)

• asynchronous (optional): A boolean indicating whether the request should be


asynchronous (true by default).
• username (optional): The username for authentication (if required).
• password (optional): The password for authentication (if required).
Use this method to set up the request before sending it.
xhr.open('GET', 'https://api.example.com/data', true);
5. XMLHttpRequest.send(content)
Sends the request to the server. The content parameter can be a string or a reference to a
document. Use this method to send the request after it has been set up. xhr.send();
Ajax workflow :
1. user clicks, invoking an event handler
2. handler's code creates an XMLHttpRequest object
3. XMLHttpRequest object requests page from server
4. server retrieves appropriate data, sends it back
5. XMLHttpRequest fires an event when data arrives
– this is often called a callback
– you can attach a handler function to this event
6. your callback event handler processes the data and displays it

SHILPA B, DEPT. OF ISE, CEC 8


FULLSTACK DEVELOPMENT (21CS62)

Properties
1. XMLHttpRequest.readyState:
An XMLHttpRequest object can have the following ready states:
• 0 →Uninitialized, meaning that open() has not been called.
• 1→Open, meaning that open() has been called but send() has not.
• 2→Sent, meaning that send() has been called, and headers and status are available, but the
response is not yet available.
• 3→Receiving, meaning that the response is being downloaded and responseText has the
portion that is presently available.
• 4→Loaded, meaning that the network operation has completed. If it has completed
successfully, this is when the web page would be updated based on the response.
2. Common HTTP Status Codes
• 100 Continue: The initial part of a request has been received, and the client can continue
with the rest of the request.
• 101 Switching Protocols: The server is switching protocols, as requested by the client.
• 200 OK: The request has succeeded.
• 201 Created: The request has been fulfilled, resulting in the creation of a new resource.
• 202 Accepted: The request has been accepted for processing, but the processing has not
been completed.

SHILPA B, DEPT. OF ISE, CEC 9


FULLSTACK DEVELOPMENT (21CS62)

• 204 No Content: The server successfully processed the request, but is not returning any
content.
• 300: The request has more than one possible response. The user or user agent (e.g., a web
browser) can choose one of them
• 301 Moved Permanently: The requested resource has been permanently moved to a new
URL.
• 302 Found: The requested resource resides temporarily under a different URL.
• 304 Not Modified: The resource has not been modified since the last request.
• 400 Bad Request: The server cannot or will not process the request due to an apparent
client error.
• 401 Unauthorized: Authentication is required and has failed or has not been provided.
• 403 Forbidden: The server understands the request but refuses to authorize it.
• 404 Not Found: The requested resource could not be found on the server.
• 500 Internal Server Error: The server encountered an unexpected condition that prevented
it from fulfilling the request.
• 502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid
response from the upstream server.
• 503 Service Unavailable: The server is not ready to handle the request, often due to being
overloaded or down for maintenance.
3. XMLHttpRequest.responseText and XMLHttpRequest.responseXML
XMLHttpRequest.responseText:
This property contains the response as text. Although the name "XMLHttpRequest" suggests
that it is primarily for XML, it is often used to fetch plain text, HTML, JSON, and other text-
based formats.
XMLHttpRequest.responseXML:
This property contains the response as a parsed XML document if the response is well-formed
XML.

SHILPA B, DEPT. OF ISE, CEC 10


FULLSTACK DEVELOPMENT (21CS62)

Questions:
• What are the 5 different XMLHttpRequest.readyStates?
• What is XMLHttpRequest.responseText and XMLHttpRequest.responseXML?

Session - 36
1. HTML
HTML (HyperText Markup Language) was the foundational technology for the web, enabling
the creation of structured documents. It was the first component that laid the groundwork for
what would become the World Wide Web.
CSS (Cascading Style Sheets) was introduced to handle the presentation aspect of web pages.
It allowed developers to separate the content (HTML) from the design and layout. This
separation enabled more flexible and manageable designs, as well as a consistent look and feel
across multiple web pages. The introduction of CSS marked a significant advancement in web
design, providing more control over the appearance of web documents.
JavaScript, originally designed to run within web browsers, added interactivity and dynamic
behavior to web pages. Over time, JavaScript has grown into a versatile language used not only
for client-side scripting but also for server-side development with environments like Node.js,
and standalone interpreters such as SpiderMonkey and Rhino.
XHTML (Extensible Hypertext Markup Language) emerged as a reformulation of HTML using
XML (Extensible Markup Language). XHTML aimed to bring stricter syntax rules and more
rigorous document structures, which made it easier for parsers to process web documents.
HTML5 is the latest evolution of the standard that defines HTML. It was designed to be more
robust and to better support multimedia and graphical content on the web without requiring
additional plugins. HTML5 introduces new elements and attributes, enhances the capability of
web applications, and provides APIs for more complex web functionality. When developing a
web project, the choice between HTML and XHTML, or any specific version of HTML,
depends on the project's requirements and existing standards.

SHILPA B, DEPT. OF ISE, CEC 11


FULLSTACK DEVELOPMENT (21CS62)

2. CSS
CSS (Cascading Style Sheets) is a language used to describe the presentation of a document
written in HTML or XHTML. It defines how elements should be displayed on the screen, on
paper, or in other media. CSS enables the separation of content (HTML) from presentation
(visual and layout aspects).
Key Features of CSS
• Separation of Concerns: CSS allows the separation of content and presentation, enabling
developers to write cleaner HTML and manage the look and feel of a site independently
from its structure.
• Cascading Rules: The "cascading" in CSS means that styles can fall back to multiple
stylesheets and rules can override others based on specificity and importance.
• Selectors: CSS provides a rich set of selectors to target HTML elements for styling. It
includes
o element selectors
o class selectors
o ID selectors
o attribute selectors
o pseudo-class selectors.
Basic CSS Syntax
• CSS rules are made up of selectors and declaration blocks:\

• Example

SHILPA B, DEPT. OF ISE, CEC 12


FULLSTACK DEVELOPMENT (21CS62)

Advantages of Using CSS


1. Improved Presentation: CSS allows for sophisticated and attractive web designs that are
consistent across multiple pages.
2. Reusability: Styles defined in an external stylesheet can be reused across different pages,
reducing redundancy and improving maintainability.
3. Accessibility: By separating content and presentation, CSS enhances the accessibility of
web content, making it easier for screen readers and other assistive technologies to interpret
the page.
4. Performance: External stylesheets can be cached by browsers, leading to faster load times
for subsequent visits.
CSS in Practice
• Semantic Markup: CSS works best with semantic HTML, where HTML elements are used
according to their intended purpose (e.g., using <table> for tabular data).
• Responsive Design: CSS enables responsive web design, allowing web pages to adapt to
different screen sizes and orientations using media queries.
• Animations and Transitions: CSS can be used to create animations and transitions,
enhancing user experience without the need for JavaScript.

SHILPA B, DEPT. OF ISE, CEC 13


FULLSTACK DEVELOPMENT (21CS62)

• Grid and Flexbox: Modern CSS includes powerful layout systems like CSS Grid and
Flexbox, which provide efficient ways to create complex, responsive layouts.
Document Object Model (DOM) :
• As far as direct human browsing is concerned, HTML and associated technologies are
vehicles to deliver a pickled Document Object Model (DOM), and nothing more.
• the DOM is the "deserialized object," or better, the "live form" of what we really deliver
to people.
• It is like deciding that you want a painting hung on a wall of a building, and then going
about getting it by adding the painting to the blueprint and asking construction
personnel to implement the specified change.
• It may be better to hang the painting on the wall directly, as is done in Ajax DOM
manipulations.

SHILPA B, DEPT. OF ISE, CEC 14


FULLSTACK DEVELOPMENT (21CS62)

Questions:
1. What is HTML and CSS?
2. What are the advantages of using CSS?

Session - 37
5. JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for
humans to read and write and easy for machines to parse and generate. It is often used for
transmitting data in web applications (e.g., sending data from the server to the client, so it can
be displayed on a web page, or vice versa).

Key Features of JSON


• Simplicity: JSON is designed to be simple to understand and use. It is built on two
structures:
• A collection of name/value pairs (often called an object or a record).

SHILPA B, DEPT. OF ISE, CEC 15


FULLSTACK DEVELOPMENT (21CS62)

• An ordered list of values (often called an array).


• Readability: JSON is text-based and easy to read and write. Its format is more compact
and readable than XML.
• Data Types: JSON supports a small number of data types:
o String (e.g., "Hello World")
o Number (e.g., 42, 3.14)
o Object (e.g., {"key": "value"})
o Array (e.g., [1, 2, 3])
o Boolean (e.g., true, false)null
Basic JSON Syntax
A JSON object is represented as a collection of key/value pairs enclosed in curly braces {}. An
array is represented as a list of values enclosed in square brackets [].

Uses of JSON
• Web APIs: JSON is commonly used to send and receive data between a server and a
web application via APIs.
• Configuration Files: JSON is often used for configuration files due to its simplicity and
readability.
• Data Storage: JSON can be used to store data in a format that is easy to work with and
parse.
• Inter-Language Communication: JSON facilitates communication between different
programming languages, each of which can easily parse JSON data.

6. IFRAMES
What are Iframes?

SHILPA B, DEPT. OF ISE, CEC 16


FULLSTACK DEVELOPMENT (21CS62)

Iframes, or inline frames, are HTML elements that allow embedding another HTML
document within the current document. This embedded document can be a separate web
page, an external content source, or any other HTML content. The iframe element is defined
using the <iframe> tag in HTML.
Syntax
<iframe src="URL" width="width" height="height"></iframe>
• src: Specifies the URL of the document to be embedded.
• width: Defines the width of the iframe.
• height: Defines the height of the iframe.
Basic Example
<iframe src="https://example.com" width="600" height="400"></iframe>
This code will embed the webpage located at https://example.com into the current
document with a width of 600 pixels and a height of 400 pixels.
Uses of Iframes
• Embedding External Content: Iframes are commonly used to embed content from
external sources, such as videos from YouTube, maps from Google Maps, or social
media feeds.
• Loading Documents: Iframes can be used to load documents, such as PDFs or other
HTML pages, within the current page without requiring a full page refresh.
• Isolating Content: Iframes provide a way to isolate content from the rest of the page.
This isolation can be useful for sandboxing content to prevent it from interfering with
the main page’s CSS or JavaScript.
Advantages of Iframes
• Content Isolation: Iframes provide a way to isolate the embedded content from the
main page. This isolation can prevent conflicts in styles or scripts between the main
page and the embedded content.
• Seamless Integration: Iframes can be used to seamlessly integrate content from
different sources into a single web page, creating a unified user experience.
• Independent Loading: The content within an iframe can load independently of the main
page. This can be useful for loading heavy content like videos or maps without slowing
down the main page.
Disadvantages of Iframes

SHILPA B, DEPT. OF ISE, CEC 17


FULLSTACK DEVELOPMENT (21CS62)

• Security Risks: Iframes can pose security risks, such as clickjacking, where a malicious
site tricks users into clicking on something different from what the user perceives.
• Performance Issues: Loading multiple iframes can slow down the page load time and
affect performance, especially if the embedded content is resource-intensive.
• Complexity in Handling: Managing and styling content within iframes can be more
complex, especially when trying to ensure consistent look and feel across different
browsers and devices.
Iframes and Ajax
Iframes can be used as an alternative or enhancement to traditional Ajax techniques for
partial page updates. While Ajax typically involves updating parts of the DOM without
refreshing the page, iframes can load entire documents, which can be beneficial in some
scenarios.

Questions
• What is JSON?
• What is iframe?

Session - 38
7. SETTINGS OF JAVA SCRIPT IN DJANGO
• Create a Static Directory: Create a directory named static within your project.
• Edit settings.py: Add the following line at the top, after import os:
DIRNAME = os.path.abspath(os.path.dirname(__file__))
• Configure MEDIA_ROOT and MEDIA_URL:
• Update MEDIA_ROOT and MEDIA_URL in settings.py
MEDIA_ROOT = os.path.join(DIRNAME, 'static/’)
MEDIA_URL = '/static/'
• Serve Static Content in Development:
At the end of settings.py, add the following code

SHILPA B, DEPT. OF ISE, CEC 18


FULLSTACK DEVELOPMENT (21CS62)

• Organize Static Content:


Create three subdirectories within static:
o static/css,
o static/images,
o static/js.
These subdirectories will be used to serve CSS, image, and JavaScript static content
respectively.

Questions
• How to create static directory?
• What changes need to be done in settings.py?

Session - 39
8. JQUERY AND BASIC AJAX
• Example: "Hello, world!" with jQuery
• Create a Django App: python manage.py startapp myapp
• Add App to Settings: Edit myproject/settings.py and add 'myapp' to the
INSTALLED_APPS list.
• Create the View:In myapp/views.py, create a view to handle the Ajax request:
from django.http import JsonResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def hello_world(request):

SHILPA B, DEPT. OF ISE, CEC 19


FULLSTACK DEVELOPMENT (21CS62)

text = request.GET.get('text', 'world')


return JsonResponse({'message': f'Hello, {text}!'})
• In myapp/urls.py, set up the URL mappings
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('hello_world/', views.hello_world, name='hello_world'),
]
• Update myproject/urls.py to include the app's URLs: path('', include('myapp.urls’)),
• Create a directory myapp/templates/ and a file index.html inside it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello, world! with Ajax</title>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("loadButton").addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/hello_world/?text=world");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};

xhr.send();
});
});
</script>
</head>

SHILPA B, DEPT. OF ISE, CEC 20


FULLSTACK DEVELOPMENT (21CS62)

<body>
<button id="loadButton">Load Content</button>
<div id="result"> <!-- Placeholder for the result --> </div>
</body>
</html>
• Run the following command to apply migrations:
python manage.py makemigration
python manage.py migrate
• python manage.py runserver
http://127.0.0.1:8000/

Creating a wrapped set:


Basic Selectors:
• $("#result"): Selects the element with the ID result.
• $("p"): Selects all paragraph elements.
• $("a"): Selects all anchor tags.
Class and Descendant Selectors:
• $("p.summary"): Selects all paragraph elements with class summary.
• $("p a"): Selects all anchor tags inside any paragraph.
• $("p > a"): Selects all anchor tags whose immediate parent is a paragraph.
• $("li > p"): Selects all paragraph tags whose immediate parent is a list item.
• $("p.summary > a"): Selects all anchor tags whose immediate parent is a paragraph with
class summary.
• $("table.striped tr:even"): Selects even-numbered rows from tables with class striped.
Differences in Selectors
• $("p a") vs. $("p > a"):
• $("p a"): Selects all anchor tags inside paragraphs, regardless of how deeply nested they
are.
• $("p > a"): Selects only anchor tags whose immediate parent is a paragraph.

SHILPA B, DEPT. OF ISE, CEC 21


FULLSTACK DEVELOPMENT (21CS62)

Using Wrapped Sets


• Definition: A wrapped set is a jQuery object that encapsulates a set of DOM elements
and a collection of operations that can be performed on them.
• Example Operation: $("table.striped tr:even").addClass("even"): Adds the class even to
even-numbered rows in tables with class striped.
Chaining Operations
• Chainable Methods: Most jQuery methods return the same wrapped set, allowing for
method chaining.
• Example:
$("table.striped tr:even").addClass("even").hide("slow").delay(1000).show("slow");
• Steps in Pseudocode:
1. Select even-numbered rows in striped tables.
2. Add the class even to them.
3. Slowly hide them.
4. Wait 1000 milliseconds.
5. Slowly show them.

9. JQUERY AJAX FACILITIES


A. $.ajax()
The $.ajax() function in jQuery is a low-level method for making HTTP requests.

B. Context
The context option in $.ajax() allows you to provide a specific value for this within the
callback functions (like success, error, complete).

SHILPA B, DEPT. OF ISE, CEC 22


FULLSTACK DEVELOPMENT (21CS62)

C. Closures
Closures are a fundamental concept in JavaScript that allow functions to retain access to
variables from the scope in which they were defined, even after that scope has closed
var closure_example = function() {
var field = 0; // Private variable
return {
get: function() {
return field;
},
set: function(newValue) {
var value = parseInt(newValue.toString());
if (isNaN(value)) {
return false; // Not a number
} else {
field = value; // Store integer value
return true; // Setter successful
}
}
};
}();
// Usage example
closure_example.set(3);
// Set the value to 3
var retrieved = closure_example.get();
// Retrieve the value, should be 3
closure_example.set(1.2);

SHILPA B, DEPT. OF ISE, CEC 23


FULLSTACK DEVELOPMENT (21CS62)

// Attempt to set a non-integer value


var assignment_was_successful = closure_example.set(1.2);
// Should return false
D. Prototypes and prototypal inheritance
Prototypes
In JavaScript, every object has a prototype, which is also an object. Prototypes serve as a
blueprint or template from which other objects inherit properties. Objects in JavaScript can
be created using object literals ({}), constructors (new Object()), or with custom constructor
functions. Each object has an internal link to another object called its prototype.
Example:
var employee = {
role: 'employee',
greet: function() {
return 'Hello, I am an ' + this.role;
}
};
var customer = Object.create(employee);
customer.role = 'customer'; // Override role for customer
console.log(customer.greet()); // Outputs: Hello, I am a customer
Prototypal Inheritance
Prototypal inheritance allows objects to inherit properties and methods from other objects.
Unlike class-based inheritance, which focuses on types and classes, prototypal inheritance
in JavaScript is more flexible and dynamic:
• Object Linkage: Objects inherit directly from other objects.
• Mutability: Objects can change their behavior dynamically by modifying their
prototypes or overriding inherited properties.
E. Data
This is the form data to pass, whether given as a string as it would appear in a GET URI,
as follows: query=pizza&page=2
or given as a dictionary, as follows: {page: 2, query: "pizza"}
F. Data Filter

SHILPA B, DEPT. OF ISE, CEC 24


FULLSTACK DEVELOPMENT (21CS62)

The dataFilter function in jQuery provides a way to process and filter the raw response data
received from an AJAX request before it is passed to the success callback. It also receives
a type parameter indicating the expected type of the response (xml, json, script, html).
This function is useful for:
• Security: Ensuring that JSON responses are safe to process and do not contain
malicious JavaScript.
• Custom Processing: Manipulating or filtering the raw data before it is parsed or further
processed.
G. Datatype
This is something you should specify, and provide a default specified value via
$.ajaxSetup(), for example: $.ajaxSetup({dataType: "text"});
The possible values are html, json, jsonp, script, text, and xml. If you do not specify a value,
jQuery will use an unsecure "intelligent guessing" that may trustingly execute any
JavaScript or JSON it is passed without any attempt to determine if it is malicious. If you
specify a dataType of text, your callback will be given the raw text which you can then test
call JSON.parse() on. If you specify a dataType of json, you will get the parsed JSON
object. So specify text even if you know you want JSON.
H. error(XMLHttpRequest, textStatus, errorThrown)
An error callback that takes up to three arguments.
For example:
$.ajax({error: function(XMLHttpRequest, textStatus, errorThrown)
{
registerError(textStatus);
}, …
});
I. success(data, textStatus, XMLHttpRequest)
A callback for success that also takes up to three arguments, but in different order.
For example:
$.ajax({success: function(data, textStatus, XMLHttpRequest) {
processData(data);
}, …
});

SHILPA B, DEPT. OF ISE, CEC 25


FULLSTACK DEVELOPMENT (21CS62)

If you want to do something immediately after the request has completed, the recommended
best practice is to specify a callback function that will pick up after the request has
completed.
J. Type
GET Method:
Typically used to retrieve or view information. Should be used when there are no significant
side effects from multiple submissions. Example: Viewing the contents of a shopping cart.
Not suitable for actions that create, modify, fulfill, or delete data.
POST Method:
Used for actions that may have significant side effects, such as creating, modifying,
fulfilling, or deleting data. Ensures actions are not repeated unintentionally (idempotency).
K. url
The URL to submit to; this defaults to the current page.
L. $.aj0axSetup()
This takes the same arguments as $.ajax(). All arguments are optional, but you can use this
to specify default values. In terms of DRY, if something can be appropriately offloaded to
$.ajaxSetup(), it probably should be offloaded to $.ajaxSetup().
M. Sample invocation
A sample invocation is as follows: $.ajaxSetup({dataType: "text", type: "POST"});
N. $.get() and $.post()
The provided text explains the usage of convenience methods in jQuery for making AJAX
requests, specifically the $.get() and $.post() methods. These methods simplify GET and
POST operations by allowing you to specify commonly used parameters without needing
the more complex key-value hash syntax required by $.ajax(). $.get() and $.post() are
simplified versions of $.ajax(). They accept parameters without requiring key-value hash
syntax.

SHILPA B, DEPT. OF ISE, CEC 26


FULLSTACK DEVELOPMENT (21CS62)

O. .load()
This is a very convenient convenience method. If you're looking for a simple, higher-level
alternative to $.ajax(), you can call this method on a wrapped set to load the results of an Ajax
call into it. There are some caveats, however. Let's give some sample invocations, look at why
.load() is attractive, and then give appropriate qualifications and warnings.
Sample Invocations of .load():
• Basic usage: $("#messages").load("/sitewide-messages");
• With data: $("#messages").load("/user-messages", "username=jsmith");
• With callback:
$("#hidden").load("/user-customizations", "username=jsmith", function(responseText,
textStatus, XMLHttpRequest) { performUserCustomizations(responseText); })

Questions
• What are the facilities of jquery Ajax?
• What are the basic selectors?
• What are descendent selectors?

Session - 40

SHILPA B, DEPT. OF ISE, CEC 27


FULLSTACK DEVELOPMENT (21CS62)

10. USING JQUERY UI AUTOCOMPLETE IN DJANGO


To integrate jQuery UI's Autocomplete feature with Django, here are the detailed steps for both
the server-side and client-side setup, including handling dynamically created elements with
Django templating and addressing progressive enhancement:
Server-Side (Django)
1. Install jQuery UI Theme: Download a theme from jQuery UI Themeroller and place
it in your static directory.
2. Include jQuery and jQuery UI: In your base template (base.html), include the
necessary stylesheets and scripts.
{% block head_css_site %}
<link rel="stylesheet" type="text/css" href="/static/css/style.css" />
<link rel="stylesheet" type="text/css" href="/static/css/smoothness/jquery-ui-
1.8.2.custom.css" />
{% endblock head_css_site %}
{% block extra_js %}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
{% endblock extra_js %}
Create a Django View for Autocomplete: Define a view that returns JSON data for the
autocomplete.
from django.http import JsonResponse
from .models import Department
def department_autocomplete(request):
if request.is_ajax():
q = request.GET.get('term', '')
departments = Department.objects.filter(name__icontains=q)
results = []
for dept in departments:
dept_json = {}
dept_json['id'] = dept.id
dept_json['label'] = dept.name
dept_json['value'] = dept.name
results.append(dept_json)

SHILPA B, DEPT. OF ISE, CEC 28


FULLSTACK DEVELOPMENT (21CS62)

data = JsonResponse(results, safe=False)


return data
return JsonResponse([], safe=False)
Update URLs: Include the autocomplete URL in your urls.py.
from django.urls import path
from .views import department_autocomplete
urlpatterns = [
path('department-autocomplete/',department_autocomplete,
name='department_autocomplete'),
# Other paths...
]
Profile View Update: Ensure your profile view passes the necessary data to the template.
from django.shortcuts import render
from .models import Entity, Department, Location
def profile(request, id):
entity = Entity.objects.get(pk=id)
departments = Department.objects.all()
locations = Location.objects.all()
context = {
'entity': entity,
'departments': departments,
'locations': locations,
}
return render(request, 'profile.html', context)
Client-Side (jQuery UI Autocomplete)
1. Autocomplete Initialization: In your profile.html template, initialize the autocomplete
widget.
<script>
$(function() {
$(".autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: "{% url 'department_autocomplete' %}",

SHILPA B, DEPT. OF ISE, CEC 29


FULLSTACK DEVELOPMENT (21CS62)

dataType: "json",
data: {
term: request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 2,
select: function(event, ui) {
// Set the selected ID in a hidden field or handle it as needed
}
});
});
</script>
Form and Select Elements: Update your form and select elements to work with jQuery
UI Autocomplete.
<form action="/ajax/save" method="POST" name="department_form"
id="department_form" target="bitbucket">
<input type="hidden" name="id" value="Entity_department_{{ entity.id }}" />
<p>Department:
<select name="department" id="department" class="autocomplete"
onchange="this.form.submit();">
<option value="department.-1">&mdash; Select &mdash;</option>
{% for department in departments %}
<option value="department.{{ department.id }}" {% if department.id ==
entity.department.id %}selected="selected"{% endif %}>{{ department.name
}}</option>
{% endfor %}
</select>
</p>
</form>

SHILPA B, DEPT. OF ISE, CEC 30


FULLSTACK DEVELOPMENT (21CS62)

Progressive Enhancement and Workarounds


• DOM Level 0 Scripting: Use inline event handlers to ensure forms submit when selections
change.
• Iframe for Form Submission: Use an iframe as a target for form submissions to handle data
without page reloads.
<iframe class="bitbucket" id="bitbucket" name="bitbucket" src="about:blank"></iframe>
<style>
.bitbucket { display: none; }
</style>
Handling Real-World Issues
When encountering issues, such as the autocomplete not saving data:
1. Debugging: Use browser developer tools to check if the callback function is being called and
if the server receives the correct data.
2. Alternative Solutions: If the current plugin doesn't work, consider other jQuery plugins or
libraries like Select2.
3. Server-Side Handling: Ensure your server-side logic correctly processes the incoming data
and saves it.
To achieve the described functionality using jQuery UI Autocomplete with Django, you need
to work on both the client-side and server-side. Here is a detailed guide to accomplish this:
Client-Side
1. Include jQuery and jQuery UI: Ensure you have included jQuery, jQuery UI, and
the theme CSS in your base template.
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Example</title>
<link rel="stylesheet"
href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<style>
#bitbucket {
display: none;
}

SHILPA B, DEPT. OF ISE, CEC 31


FULLSTACK DEVELOPMENT (21CS62)

</style>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
Create a Django Template: Create a template that includes the form elements you need.
For example, create a template called profile.html.
{% extends "base.html" %}
{% block content %}
<iframe id="bitbucket" name="bitbucket" src="about:blank"></iframe>
<form action="{% url 'save' %}" method="POST" name="department_form"
id="department_form" target="bitbucket">
{% csrf_token %}
<input type="hidden" name="id" value="Entity_department_{{ entity.id }}">
<p>Department:
<select name="department" id="department" class="autocomplete"
onchange="this.form.submit();">
<option value="department.-1">None</option>
{% for department in departments %}
<option value="department.{{ department.id }}" {% if department.id ==
entity.department.id %}selected="selected"{% endif %}>
{{ department.name }}
</option>
{% endfor %}
</select>
</p>
</form>

<form action="{% url 'save' %}" method="POST" name="location_form"


id="location_form" target="bitbucket">
{% csrf_token %}

SHILPA B, DEPT. OF ISE, CEC 32


FULLSTACK DEVELOPMENT (21CS62)

<input type="hidden" name="id" value="Entity_location_{{ entity.id }}">


<p>Location:
<select name="location" id="location" class="autocomplete"
onchange="this.form.submit();">
<option value="location.-1">None</option>
{% for location in locations %}
<option value="location.{{ location.id }}" {% if location.id ==
entity.location.id %}selected="selected"{% endif %}>
{{ location.identifier }}
</option>
{% endfor %}
</select>
</p>
</form>

<form action="{% url 'save' %}" method="POST" name="reports_to_form"


id="reports_to_form" target="bitbucket">
{% csrf_token %}
<input type="hidden" name="id" value="Entity_reports_to_{{ entity.id }}">
<p>Reports to:
<select name="reports_to" id="reports_to" class="autocomplete"
onchange="this.form.submit();">
<option value="reports_to_-1">None</option>
{% for reports_to in reports_to_candidates %}
<option value="reports_to_{{ reports_to.id }}" {% if reports_to.id ==
entity.reports_to.id %}selected="selected"{% endif %}>
{{ reports_to.name }}
</option>
{% endfor %}
</select>
</p>
</form>
{% endblock %}

SHILPA B, DEPT. OF ISE, CEC 33


FULLSTACK DEVELOPMENT (21CS62)

Initialize jQuery UI Autocomplete: Create a JavaScript block to initialize the


autocomplete functionality.
<script>
$(document).ready(function() {
$.widget("custom.combobox", {
_create: function() {
var select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = $("<input>").insertAfter(select)
.val(value)
.autocomplete({
delay: 0,
minLength: 0,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function() {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
select: function(event, ui) {
ui.item.option.selected = true;
$(ui.item.option).parent().trigger("change");
},
change: function(event, ui) {
if (!ui.item) {

SHILPA B, DEPT. OF ISE, CEC 34


FULLSTACK DEVELOPMENT (21CS62)

var matcher = new RegExp("^" +


$.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function() {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.append("<div>" + item.label + "</div>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.tooltip()
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},

SHILPA B, DEPT. OF ISE, CEC 35


FULLSTACK DEVELOPMENT (21CS62)

text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.on("click", function() {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}

// pass empty string as value to search for, displaying all results


input.autocomplete("search", "");
input.focus();
});
}
});

$(".autocomplete").combobox();
});
</script>
Server-Side
1. Create Django Views: Create views in Django to handle the AJAX requests and save
the data.
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse, HttpResponse
from .models import Entity, Location, Department
def save(request):
if request.method == 'POST':
entity_id = request.POST.get('id')
field, entity_id = entity_id.rsplit('_', 1)
value = request.POST.get('value')
entity = get_object_or_404(Entity, id=entity_id)

SHILPA B, DEPT. OF ISE, CEC 36


FULLSTACK DEVELOPMENT (21CS62)

if field == 'department':
entity.department_id = value
elif field == 'location':
entity.location_id = value
elif field == 'reports_to':
entity.reports_to_id = value
entity.save()
return JsonResponse({'status': 'ok'})
return HttpResponse(status=400)
Update URL Configuration: Add the URL for the AJAX view to your urls.py.
from django.urls import path
from . import views
urlpatterns = [
path('ajax/save/', views.save, name='save'),
]
Testing and Refinement
1. Test the Functionality: Test the form in your browser, ensuring that the autocomplete
works and that changes are saved correctly to the server.
2. Debug Issues: If any issues arise, use browser developer tools to check for JavaScript
errors, inspect network requests, and verify that the correct data is being sent and
received.
3. Refine the Solution: Improve user experience by tweaking the UI elements, adding
better error handling, and ensuring accessibility.
By following these steps, you should have a robust implementation of jQuery UI Autocomplete
in a Django application, with progressive enhancement and server-side handling of AJAX
requests.
• Changing Default Option Value:
Updated the default select option to "None" for better autocomplete user experience.
• HTML Form Structure:
Various fields such as department, location, and reports_to are placed within individual
paragraphs for better whitespace usage.
Example for Department field
<p>Department:

SHILPA B, DEPT. OF ISE, CEC 37


FULLSTACK DEVELOPMENT (21CS62)

<select name="department" id="department" class="autocomplete"


onchange="update_autocomplete('Entity_department_{{ entity.id}}', this.value);">
<option value="department.-1">None</option>
{% for department in departments %}
<option value="department.{{ department.id }}">{{ department.name }}</option>
{% endfor %}
</select>
</p>
Server-side Code for Handling Ajax Requests:
• The save view processes both GET and POST requests, identifies the field being updated,
performs necessary validation, and updates the database accordingly.
• Specific handling for department, location, and reports_to fields, and general handling for
other fields.
• Example for updating department
elif html_id.startswith(u'Entity_department_'):
entity_id = int(html_id[len(u'Entity_department_'):])
department_id = int(value[len(u'department.'):])
entity = directory.models.Entity.objects.get(pk = entity_id)
if department_id == -1:
entity.department = None
else:
entity.department = directory.models.Entity.objects.get(pk = department_id)
entity.save()
return HttpResponse(value)
Client-side JavaScript for Autocomplete:
• jQuery UI's combobox widget is used to convert selects to autocompletes.
• Custom update_autocomplete function makes Ajax calls to update values.
• Example implementation:
$(function() {
$(".autocomplete").combobox();
$(".autocomplete").toggle();
function update_autocomplete(html_id, value) {
$.ajax({

SHILPA B, DEPT. OF ISE, CEC 38


FULLSTACK DEVELOPMENT (21CS62)

data: {
id: html_id,
value: value,
},
url: "/ajax/save",
success: function(data) {
send_notification(data);
}
});
}
});
Error Handling and Notifications:
• AJAX setup to display Django error pages as notifications for better debugging.
• Notification styling and dynamic message display time
function send_notification(message) {
$("#notifications").html("<p>" + message + "</p>");
setTimeout("$('#notifications').show('slow').delay(" + (5000 + message.length * 2) +
").hide('slow');", 0);
}
Improved User Experience:
• Autocomplete fields offer both a dropdown select and an autocomplete input.
• Provides a more polished and user-friendly interface for managing entity fields.

Questions
• What change was made to the default option value in the select elements, and why?
• How does the server-side save view handle different types of fields being updated via
Ajax requests?
• What function is used to convert select elements into autocompletes, and how is it
implemented?
• How are errors handled during Ajax requests in the client-side JavaScript?

SHILPA B, DEPT. OF ISE, CEC 39

You might also like