0% found this document useful (0 votes)
12 views15 pages

MODULE 51 - FSD-Notes

The document provides notes for a Bachelor of Engineering course on Full Stack Development, covering AJAX, JavaScript, jQuery, and Django integration. It includes explanations of key technologies, methods, and properties related to AJAX, as well as practical examples for creating a registration page using AJAX without page refresh. Additionally, it outlines the necessary configurations in Django settings and includes code snippets for views, models, and templates.

Uploaded by

Ranjitha J
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)
12 views15 pages

MODULE 51 - FSD-Notes

The document provides notes for a Bachelor of Engineering course on Full Stack Development, covering AJAX, JavaScript, jQuery, and Django integration. It includes explanations of key technologies, methods, and properties related to AJAX, as well as practical examples for creating a registration page using AJAX without page refresh. Additionally, it outlines the necessary configurations in Django settings and includes code snippets for views, models, and templates.

Uploaded by

Ranjitha J
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/ 15

SJB Institute of Technology, Bangalore – 60

BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Name of the Course: FSD (18CS745)


NOTES – Module-5

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.

XHTML HttpRequest and Response


The XMLHttpRequest object can be used to request data from a web server.
The XMLHttpRequest object is a developers dream, because you can:
• Update a web page without reloading the page
• Request data from a server - after the page has loaded
• Receive data from a server - after the page has loaded
• Send data to a server - in the background
1. Methods
2. Properties
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

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

JavaScript Object Notation


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.

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.

Settings of Java Script in Django


Create a directory named static within your project. (Note that other names may be used, but do not use
media, as that can collide with administrative tools.)
Edit the settings.py file, and add the following at the top, after
import os: DIRNAME = os.path.abspath(os.path.dirname(__file__))
Change the settings of MEDIA_ROOT and MEDIA_URL: MEDIA_ROOT = os.path.join(DIRNAME,
'static/') … MEDIA_URL = '/static/’
At the end of the settings.py file, add the following: if settings.DEBUG:
urlpatterns += patterns('django.views.static’,
(r'^%s(?P.*)$' % (settings.MEDIA_URL[1:],), 'serve', { 'document_root’:
settings.MEDIA_ROOT,
'show_indexes': True }),)
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

CHAPTER 2

jQuery and Basic AJAX

Creating a wrapped set


select nodes from the DOM more or less as one would expect:
$("#result#") selects the item with HTML ID result
$("p") selects all paragraph elements
$("p.summary") selects all paragraph elements with class summary
$("a") selects all anchor tags
$("p a") selects all anchor tags in a paragraph
$("p > a") selects all anchor tags whose immediate parent is a paragraph tag
$("li > p") selects all p tags whose immediate parent is a li tag
$("p.summary > a") selects all anchor tags whose immediate parent is a paragraph tag with class summary
$("table.striped tr:even") selects even-numbered rows from all tables belonging to class striped

jQuery AJAX Facilities

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"});

8. error(XMLHttpRequest, textStatus, errorThrown) - An error callback that takes up to three


arguments. For example:

$.ajax({error: function(XMLHttpRequest, textStatus, errorThrown)

registerError(textStatus);

}, …

});

9. 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);

}, …
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().

13. Sample invocation - A sample invocation is as follows:

$.ajaxSetup({dataType: "text", type: "POST"});

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

# Create your views here.


from django.http import HttpResponse
from Module51.models import Course, Student
def regaj(request):
if request.method == "POST":
sid=request.POST.get("sname")
cid=request.POST.get("cname")
student=Student.objects.get(id=sid)
course=Course.objects.get(id=cid)
res=student.enrolment.filter(id=cid)
if res:
return HttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
return HttpResponse("<h1>Student enrolled successfully</h1>")

else:
students=Student.objects.all()
courses=Course.objects.all()

return render(request,"regaj.html",{"students":students, "courses":courses})

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 folder – jquery3.7.1.min.js


Setting.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

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

from Module51.views import regaj


from Module52.views import course_search_ajax

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 files (CSS, JavaScript, Images)


# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIR = [os.path.join(BASE_DIR, 'Module52/static')]

python manage.py makemigrations


python manage.py migrate
python manage.py runserver
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

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

# Create your models here.


class Course(models.Model):
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

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+")"

template – course_search_aj.html, selected_students.html


course_search_aj.html
{% load static %}
<html>
<body>
<form method="POST" action="">
Courses
{% csrf_token %}
<select name="cname" id="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<input type="button" value="Search" id="serbtn">
<span id="result"></span>
</form>
</body>
<script src="{% static 'jquery.min.js' %}"></script>
<script>
$(document).ready(function(){
$("#serbtn").click(function(){
var cname = $("#cname").val();
$.ajax({
url: "/course_search_ajax/",
type: "POST",
data: {cname:cname,csrfmiddlewaretoken:"{{csrf_token }}"},
success: function(response){
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

$("#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

from Module51.views import regaj


from Module52.views import course_search_ajax
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

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

You might also like