0% found this document useful (0 votes)
15 views33 pages

FSD Module-5 Notes

Uploaded by

Shreya Rangachar
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)
15 views33 pages

FSD Module-5 Notes

Uploaded by

Shreya Rangachar
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/ 33

MODULE –5

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

Course Objectives:

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

Course Outcomes (COs):

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

DR G.S HIREMATH, DEPT. OF CSE, CEC 1


Session – 53
1. Ajax Solution

Ajax: Another overlaid function


What exactly is this overlaid function?
Ajax is a way of using client-side technologies to talk with a server and perform partial page
updates. Updates may be to all or part of the page, or simply to data handled behind the
scenes. It is an alternative to the older paradigm of having a whole page replaced by a new
page loaded when someone clicks on a link or submits a form. Partial page updates, in Ajax,
are associated with Web 2.0, while whole page updates are associated with Web 1.0; it is
important to note that "Web 2.0" and "Ajax" are not interchangeable. Web 2.0 includes more
decentralized control and contributions besides Ajax, and for some objectives it may make
perfect sense to develop an e-commerce site that uses Ajax but does not open the door to the
same kind of community contributions as Web 2.0.

Some of the key features common in Web 2.0 include:


o Partial page updates with JavaScript communicating with a server and
rendering to a page
o An emphasis on user-centered design
o Enabling community participation to update the website
o Enabling information sharing as core to what this communication allows

DR G.S HIREMATH, DEPT. OF CSE, CEC 2


DR G.S HIREMATH, DEPT. OF CSE, CEC 3
DR G.S HIREMATH, DEPT. OF CSE, CEC 4
Ajax: Asynchronous JavaScript and XML
⮚ AJAX, which stands for asynchronous JavaScript and XML, is a set of technologies
used on the client-side to send and retrieve data from the server asynchronously.
⮚ not a programming language; a particular way of using JavaScript
⮚ downloads data from a server in the background
⮚ allows dynamically updating a page without making the user wait
⮚ avoids the "click-wait-refresh" pattern
⮚ JavaScript includes an XMLHttpRequest object that can fetch files from a web server
⮚ it can do this asynchronously (in the background, transparent to user)
⮚ the contents of the fetched file can be put into current web page using the
DOM(Document Object Model )
⮚ What exactly is this overlaid function?(Eg:Voice)

⮚ Ajax is a way of using client-side technologies to talk with a server and perform
partial page updates.

DR G.S HIREMATH, DEPT. OF CSE, CEC 5


Synchronous vs Asynchronous web communication

DR G.S HIREMATH, DEPT. OF CSE, CEC 6


Web 1.0 & Web 2.0

Some of the key features common in Web 2.0 include:


– Partial page updates with JavaScript communicating with a server and rendering to a
page

DR G.S HIREMATH, DEPT. OF CSE, CEC 7


– An emphasis on user-centered design
– Enabling community participation to update the website
– Enabling information sharing as core to what this communication allows

XMLHttpRequest- Methods:

Properties :
1. XMLHttpRequest.onreadystatechange, & XMLHttpRequest.readyState
• A bare-bones XMLHttpRequest object can be expected to have the following
properties:
– XMLHttpRequest.onreadystatechange - which is called without argument each
time the ready state of XMLHttpRequest changes.
• An XMLHttpRequest object can have five ready states:
– Uninitialized, meaning that open() has not been called.
– Open, meaning that open() has been called but send() has not.
– Sent, meaning that send() has been called, and waiting
– Receiving, meaning that the response is being downloaded

DR G.S HIREMATH, DEPT. OF CSE, CEC 8


– Loaded, meaning that the network operation has completed
2. XMLHttpRequest.responseText & XMLHttpRequest.responseXML
– responseText - to fetch raw binary data,
– responseXML object is commonly used to fetch not only XML but XHTML,
HTML, plain text, and JSON.
3. XMLHttpRequest.status & XMLHttpRequest.statusText
– The status field contains the HTTP code, such as 200 for OK;
– the statusText field has a short text description, like OK.

Technologies used in Ajax


• HTML/XHTML and CSS - Representation
• DOM - Document Object Model
• XML or JSON(JavaScript Object Notation ) – data Representation
• Dijango – Frame-work
• XMLHttpRequest – Data processing
• Javascript – Jquery
• Ajax = (HTML+XHTML+XML+JSON+JS+DOM+DJ)

HTML & XHTML

DR G.S HIREMATH, DEPT. OF CSE, CEC 9


JavaScript Object Notation (JSON)
• JSON is a brilliantly simple idea.
• JSON is clear, simple, and concise enough that not only is it a format of choice for
JavaScript, but it is gaining traction in other languages, and it is being used for
communication between languages that need a (simple, added) parser to parse JSON.
• However, JSON is turning out to have a much broader impact than the initial "in
communicating with JavaScript, just give it code to declare the object being
communicated that can simply be evaluated to construct the object."

DR G.S HIREMATH, DEPT. OF CSE, CEC 10


• JSON is a lightweight format for storing and transporting data
• JSON is often used when data is sent from a server to a web page
• JSON is "self-describing" and easy to understand

Features of XML :
o XML focuses on data rather than how it looks
o Easy and efficient data sharing
o Compatibility with other markup language HTML
o Supports platform transition

DR G.S HIREMATH, DEPT. OF CSE, CEC 11


o Allows validation
o XML supports Unicode

Cascading Style Sheets (CSS) :


• Cascading Style Sheets (CSS) may have introduced some new possibilities for
presentation.
• CSS as it added good engineering to styling and make the combination of semantic
markup and attractive appearance a far more attainable goal.
• In Ajax, as for the rest of the web, the preferred practice is to use semantic, structural
markup, and then add styles in a stylesheet (not inline) so that a particular element,
optionally belonging to the right class or given the right ID, will have the desired
appearance.

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.

DR G.S HIREMATH, DEPT. OF CSE, CEC 12


iframes and other Ajax variations :
• Ajax includes several variations.
• Comet and iframes are two of many possible variations on the basic Ajax technique.

DR G.S HIREMATH, DEPT. OF CSE, CEC 13


• Comet for instance, is a variation on standard Ajax in which either an
XMLHttpRequest object's connection to a server is kept open and streaming
indefinitely, or
• a new connection is opened whenever an old one is closed, creating an Ajax
environment in which the server as well as the client can push material.
• One much more essential Ajax variation has to do with loading documents into
seamlessly integrated iframes instead of making DOM manipulations to a single,
frame-free web page.

JavaScript/Ajax Libraries :
• https://code.jquery.com/jquery.min.js
• jquery.min.js – Js Library
• JavaScript libraries offer several advantages.
• They can reduce chores and boilerplate code, significantly lessening the pain of
JavaScript, and provide a more uniform interface.
• They can also provide (for instance) ready-made widgets; a jQuery
• And on a broad scale, they can let the JavaScript you write be higher-level and a little
more Pythonic.

Setting JavaScript and other static content in place :


• For the development server, putting static content, including images, CSS, and static
content, is straightforward. for development use, the following steps will serve up
static content:

DR G.S HIREMATH, DEPT. OF CSE, CEC 14


Front & Back End :
• REST API integrated with frontend technology using AJAX and Jquery.
• Representational state Transfer(REST)

JQuery :
• jQuery is a lightweight, "write less, do more", JavaScript library.
• The purpose of jQuery is to make it much easier to use JavaScript on your website.
• jQuery takes a lot of common tasks that require many lines of JavaScript code to
accomplish, and wraps them into methods that you can call with a single line of code.
• jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX
calls and DOM manipulation.
• The jQuery library contains the following features:
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities

DR G.S HIREMATH, DEPT. OF CSE, CEC 15


Jquery Syntax :

Jquery Selectors :

DR G.S HIREMATH, DEPT. OF CSE, CEC 16


DR G.S HIREMATH, DEPT. OF CSE, CEC 17
Jquery Example :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

Ajax workflow :
1. user clicks, invoking an event handler
2. handler's code creates an XMLHttpRequest object

DR G.S HIREMATH, DEPT. OF CSE, CEC 18


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

DR G.S HIREMATH, DEPT. OF CSE, CEC 19


Http ready states :
0: The request is uninitialized
Before calling open()
1: The request is set up, but hasn’t been sent
Before calling send()
2: The request is sent and is being processed
Sometimes you can get content headers now
3: The request is being processed
The server hasn’t finished with its response
4: The response is complete

jQuery Ajax facilities :


• jQuery provides good facilities both for Ajax and other JavaScript usage. The API is
excellent and can be bookmarked from http://api.jquery.com/.
• $.ajax()
• The most foundational and low-level workhorse in jQuery is $.ajax().

• jQuery provides several methods for AJAX functionality.


• With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a
remote server using both HTTP Get and HTTP Post –
• And you can load the external data directly into the selected HTML elements of your
web page!
• The load() method loads data from a server and puts the returned data into the
selected element.
• The $.get() method requests data from the server with an HTTP GET request.

DR G.S HIREMATH, DEPT. OF CSE, CEC 20


• The $.post() method requests data from the server using an HTTP POST request.

Jquery get example :


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>

Jquery post example :


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",

DR G.S HIREMATH, DEPT. OF CSE, CEC 21


city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>

$.ajax() :
• The most foundational and low-level workhorse in jQuery is $.ajax().
• It takes the arguments as shown in the following Sample invocation.
• Default values can be set with $.ajaxSetup(), as discussed below:

Some of the fields that can be passed :

DR G.S HIREMATH, DEPT. OF CSE, CEC 22


• Context
• The context, available as the variable this, can be used to give access to
variables in callbacks.
• The following code prompts for the user's name and e-mail address and
provides them in a context, anonymously,
• so that the data are available to the callback function but are never a part of the
global namespace.

• Closures
• Closures represent a key concept in core JavaScript, along with other things
such as functions, objects, and prototypes.
• Closures are part of the conceptual landscape and they are the basis on how to
effectively create an object with private fields.
• example : using a closure to create an object with private variables, which
creates an object that stores an integer value, has a getter and setter, but in Java
fashion ensures that the field can only have an integer value.

DR G.S HIREMATH, DEPT. OF CSE, CEC 23


Prototypes and prototypal inheritance :
• Prototypes and prototypal inheritance are a basis for object-oriented programming,
with inheritance, but without classes.
• In Java, certain features of a class are fixed.
• In Python, an object inherits from a class but features that are fixed in Java cannot be
overridden.
• In JavaScript, we go one step further and say that objects inherit from other objects.
• Prototypal inheritance is more like the evolutionary picture of single-celled organisms
that can mutate, reproduce asexually by cell division, and pass on (accumulated)
mutations when they divide.
• In JavaScript, an object's prototype is set by, for instance:
• customer.prototype = employee;
• Redefine members for a customer when one wants to change from the attributes of an
employee.
• Also note that this inheritance may or may not mean moving from more general to
more specific; inheritance may better be seen as "customer mutates from employee"
than "customer is a more specific type of employee."

parameters of $.ajax() :

DR G.S HIREMATH, DEPT. OF CSE, CEC 24


• 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"}

• dataFilter
– This is a reference to a function that will be passed two arguments:
• the raw response given by an XMLHttpRequest, and
• a type (xml, json, script, or html).
– This offers an important security hook.
– One of the cardinal rules of security on both the client-side and server-side is
to treat all input as guilty until proven innocent of being malicious.
• Even though it is a "double work" chore, user input should both be validated at the
client-side and the server-side:
– client-side as a courtesy to the user to improve the user experience and not as
trustworthy security,
– and on the server side as a security measure against malicious data even if it
is malformed malicious data that no normal web browser would send.
• jQuery does not automatically include functionality to test whether something served
up as JSON is malicious, and methods like .getJSON() trustingly execute what might
contain malicious JavaScript

• 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 cause security issues.

DR G.S HIREMATH, DEPT. OF CSE, CEC 25


Web services :
⮚ A web service is a set of open protocols and standards that allow data to be
exchanged between different applications or systems.
⮚ Web services can be used by software programs written in a variety of programming
languages and running on a variety of platforms to exchange data via computer
networks such as the Internet in a similar way to inter-process communication on a
single computer
⮚ A Web service is a web application that can communicate with other web-based
applications over a network.
⮚ Web services implementation allows two web applications developed in different
languages to interact with each other using a standardized medium like XML, SOAP,
HTTP etc

DR G.S HIREMATH, DEPT. OF CSE, CEC 26


DR G.S HIREMATH, DEPT. OF CSE, CEC 27
Building Rest API using Dijango :

DR G.S HIREMATH, DEPT. OF CSE, CEC 28


Using jQuery UI Autocomplete in Django Templates :
• Adding autocomplete: first attempt
• What specific theme can be used is customizable, but autocomplete and other
plugins require some theme such as jQuery UI Theme roller provides.
• jQuery UI Themeroller, which lets you customize and tweak a theme , is
available at: http://jqueryui.com/themeroller/
• When you have made any customizations and downloaded a theme, you can
unpack it under your static content directory

• Progressive enhancement, a best practice


• "Progressive enhancement," in a nutshell, means that as much as possible you
build a system that works without JavaScript or CSS,
• with semantic markup and similar practices, then add appearance with CSS,
and then customize behavior with JavaScript.
• example of customizing behavior is to make a sortable table which is
originally sortable,
• in Web 1.0 fashion, by clicking on a link in a table header which will load a
version of the table sorted by that link.
• Then the links are "hijaxed" by using JavaScript to sort the table purely by
JavaScript manipulations of the page,

DR G.S HIREMATH, DEPT. OF CSE, CEC 29


• so that if a user does not have JavaScript on, clicking on the links loads a fresh
page with the table sorted by that column,
• the same end result is achieved without waiting on a network hit.
• In this case, we mark up and populate a dropdown menu of available entities,
which the JavaScript will hide and replace with an autocomplete box.
• The option tags follow a naming convention of fieldname.id;
• Here we follow the same basic formula for department, location, and reports_to. We
produce a list of all available options.
• The first entry is for no selected department/location/reports_to;
• as a courtesy to the user we add selected="selected" to the presently selected value so
that the form is smart enough to remember the last selected value, rather than
defaulting to a (presumably unwanted) choice each time the user visits it.

• This much of the code is run once and creates the beginning of the containing
paragraph, sets a strong tag, and creates the entry for no department selected.
• Then we loop through the list of departments, creating an option that has a value of
"department." followed by the id of the entity provided as a department.

DR G.S HIREMATH, DEPT. OF CSE, CEC 30


• The location and reports_to are handled similarly:

DR G.S HIREMATH, DEPT. OF CSE, CEC 31


• Our profile page is modified to provide more variables to the template.

• This provides nice-looking autocomplete functionality like:

DR G.S HIREMATH, DEPT. OF CSE, CEC 32


DR G.S HIREMATH, DEPT. OF CSE, CEC 33

You might also like