MODULE 51 - FSD-Notes
MODULE 51 - FSD-Notes
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Textbook-2
Chapter 1
Ajax Solution
Java Script
XHTML HttpRequest and Response
HTML
CSS
JSON
iFrames
Settings of Java Script in Django
Chapter 2
jQuery and Basic AJAX
jQuery AJAX Facilities
Chapter 7
Using jQuery UI Autocomplete in Django
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
CHAPTER 1
AJAX SOLUTION
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.
Ajax is a way of using client-side technologies to talk with a server and perform partial page updates.
• 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.
Technologies used -HTML/XHTML and CSS, DOM,XML or JSON,Dijango,XMLHttpRequest,
Javascript
JAVA SCRIPT
JavaScript deserves pride of place, and while it is possible to use VBScript for Internet Explorer as much
more than a proof of concept, for now if you are doing Ajax, it will almost certainly be Ajax running
JavaScript as its engine. Your application will have JavaScript working with XMLHttpRequest,
JavaScript working with HTML, XHTML, or HTML5.
The first source of pain is some of the language decisions in JavaScript:
The Wikipedia article says it was designed to resemble Java but be easier for non-programmers, a
decision reminiscent of SQL and COBOL.
The Java programmer who finds the C-family idiom of for(i = 0; i < 100; ++i) available will be
astonished to find that the functions are clobbering each other's assignments to i until they are explicitly
declared local to the function by declaring the variables with var. There is more pain where that came
from.
The second source of pain is quite different. It is a pain of inconsistent implementation: for example- the
pain of, "Write once, debug everywhere." Strictly speaking, this is not JavaScript's fault; browsers are
inconsistent.
1. Methods
1. XMLHttpRequest.abort() This cancels any active request.
2. XMLHttpRequest.getAllResponseHeaders() This returns all HTTP response headers sent with
the response.
3. XMLHttpRequest.getResponseHeader(headerName)
4. XMLHttpRequest.open(method, URL, asynchronous)
5. XMLHttpRequest.send(content)
Content can be a string or a reference to a document
2. Properties
A bare-bones XMLHttpRequest object can be expected to have the following properties:
1. XMLHttpRequest.onreadystatechange, XMLHttpRequest.readyState - 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 headers and status are available, but
the response is not yet available.
• Receiving, meaning that the response is being downloaded and responseText.
• Loaded, meaning that the network operation has completed. If it has completed
successfully (that is, the HTTP status stored in XMLHttpRequest.status is 200),
this is when the web page would be updated based on the response.
2. XMLHttpRequest.responseText, XMLHttpRequest.responseXML.
3. XMLHttpRequest.status, XMLHttpRequest.statusText.
HTML
HTML and XHTML are the markup language for the web. JavaScript and CSS were introduced in
relation to HTML. The JavaScript is a very interesting language independent of web browsers and using
standalone interpreters such as SpiderMonkey and Rhino. However, HTML was on the scene first and
other players on the web exist in relation to HTML's story.
CSS
Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document
written in HTML or XML (including XML dialects such as XHTML). CSS describes how elements
should be rendered on screen, on paper, in speech, or on other media. CSS is among the core languages
of the open web.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
JSON
iFrames
Ajax includes several variations; 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. This is used, for instance, in some instant messaging implementations.
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.
Example – Gmail
Compose Mail, or a filter, or a message subject - Ajax update.
Ajax clone of Gmail - back
In Gmail, the browser's Back button works with surgical accuracy, and the reason it can do something much
better than take you back to the login screen is that Gmail is carefully implemented with iframes, and every
change that the Back button can undo is implemented by a fresh page load in one of the seamlessly integrated
iframes.
CHAPTER 2
1. $.ajax() - The most foundational and low-level workhorse in jQuery is $.ajax(). Default values
can be set with $.ajaxSetup().
2. Context - The context, available as the variable this, can be used to give access to variables
in callbacks, even if they have fallen out of scope.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
3. Closures - The principle at play is the principle of closures. The wrong way, perhaps, to learn
about closures is to look for academic-style introductions to what you need to know in order to
understand them. For example – closure stores not the anonymous function but its return value.
4. 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.
5. Data - This is the form data to pass, whether given as a string as it would appear in a GET URI.
6. 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: JSON can be passed to an eval(), but malicious JavaScript that is
passed in place of JSON data can also be passed to an eval().
7. Datatype - This is something you should specify, and provide a default specified value via
$.ajaxSetup(), for example: $.ajaxSetup({dataType: "text"});
registerError(textStatus);
}, …
});
9. success(data, textStatus, XMLHttpRequest) - A callback for success that also takes up to three
arguments, but in different order. For example:
processData(data);
}, …
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
});
10. type - The type of the request, for example GET, POST, and so on.
11. url - The URL to submit to; this defaults to the current page.
12. $.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().
14. $.get() and $.post() - These are convenience methods for $.ajax() that allow you to specify
commonly used parameters without key-value hash syntax and are intended to simplify GET
and POST operations.
15. .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.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
CHAPTER 7
LAB PROGRAMS
Develop a registration page for student enrolment as done in Module 2 but without page refresh
using AJAX.
Views.py
from django.shortcuts import render
else:
students=Student.objects.all()
courses=Course.objects.all()
Models.py
from django.db import models
class Course(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField(blank=True, null=True)
def __str__(self):
return self.course_name
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
class Student(models.Model):
student_usn=models.CharField(max_length=20)
student_name=models.CharField(max_length=100)
student_sem=models.IntegerField()
enrolment=models.ManyToManyField(Course)
def __str__(self):
return self.student_name+"("+self.student_usn+")"
template file
regaj.html
{% load static %}
<html>
<body>
<form method="post" action="">
{% csrf_token %}
Student Name
<select name="sname" id="sname">
{%for student in students %}
<option value="{{student.id}}">{{student.student_name}}</option>
{% endfor %}
</select><br>
Course Name
<select name="cname" id="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select><br>
<span id="ans"></span>
<input type="button" value="Enroll" id="ebtn">
</form>
<script src="{% static 'jquery.min.js' %}"></script>
<script>
$(document).ready(function(){
$("#ebtn").click(function(){
var sname = $("#sname").val();
var cname = $("#cname").val();
$.ajax({
type: "POST",
url: "/regaj/",
data: {sname: sname, cname: cname,
csrfmiddlewaretoken:"{{ csrf_token}}"
},
success: function(response){
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
$("#ans").html(response)
}
});
});
});
</script>
</body>
</html>
STATIC_URL = 'static/'
STATICFILES_DIR = [os.path.join(BASE_DIR, 'Module52/static')]
Urls.py
from django.urls import include, path
from django.urls import path,reverse_lazy
from django.views.generic import CreateView
urlpatterns = [
path('admin/', admin.site.urls),
path('regaj/',regaj),
path('course_search_ajax/', course_search_ajax),
]
Setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Module52',
'Module51'
]
TEMPLATES = [
{
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'Module51/template')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'stud',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
}
STATIC_URL = 'static/'
STATICFILES_DIR = [os.path.join(BASE_DIR, 'Module52/static')]
Develop a search application in Django using AJAX that displays courses enrolled by a student
being searched.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from Module51.models import Course,Student
def course_search_ajax(request):
if request.method=="POST":
cid=request.POST.get("cname")
s=Student.objects.all()
student_list=list()
for student in s:
if student.enrolment.filter(id=cid):
student_list.append(student)
if len(student_list)==0:
return HttpResponse("<h1>No Students enrolled</h1>")
return render(request,"selected_students.html",{"student_list":student_list})
else:
courses=Course.objects.all()
return render(request,"course_search_aj.html",{"courses":courses})
Models.py
from django.db import models
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField(blank=True, null=True)
def __str__(self):
return self.course_name
class Student(models.Model):
student_usn=models.CharField(max_length=20)
student_name=models.CharField(max_length=100)
student_sem=models.IntegerField()
enrolment=models.ManyToManyField(Course)
def __str__(self):
return self.student_name+"("+self.student_usn+")"
$("#result").html(response);
}
});
});
});
</script>
</html>
Selected_students.html
<html>
<body>
<table border>
<tr>
<th>Student Name</th>
<th>Student USN</th>
<th>Sem</th>
</tr>
{% for student in student_list %}
<tr>
<td>{{student.student_name}}</td>
<td>{{student.student_usn}}</td>
<td>{{student.student_sem}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
Urls.py
from django.urls import include, path
from django.urls import path,reverse_lazy
from django.views.generic import CreateView
urlpatterns = [
path('admin/', admin.site.urls),
path('regaj/',regaj),
path('course_search_ajax/', course_search_ajax),
]
Prepared By,
Ranjitha J
Assistant
ProfessorDept, of
ISE
SJB Institute of Technology