Module 5
Module 5
MODULE – 5
JQUERY AND AJAX INTEGRATION 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.
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.
Questions
• What are the different technologies in Ajax?
• What are the key components in Django- Python Web Framework?
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
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.
Questions
• What is the full form of Ajax?
• What are the use cases of Ajax?
• What is java script?
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.
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.
• 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.
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.
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
• 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.
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).
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?
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
• 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
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):
xhr.send();
});
});
</script>
</head>
<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/
B. Context
The context option in $.ajax() allows you to provide a specific value for this within the
callback functions (like success, error, complete).
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);
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);
}, …
});
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.
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
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">— Select —</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>
</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>
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;
}
$(".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)
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:
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?