AJAX - Object-Oriented JavaScript
AJAX - Object-Oriented JavaScript
DCA8241
Unit 8
AJAX – Object-Oriented JavaScript
Table of Contents
3 Prototype - - 5-6
4 Object-Oriented XML Http Request 1, 2 1 7-9
5 Model-View-Control (MVC) 3, 4 2 10 - 12
6 JavaScript Object Notation (JSON) 5, 6 3 13 - 20
7 Summary - - 21
8 Glossary - - 22
9 Terminal Questions - - 22
10 Answer Keys - - 23 - 24
11 Suggested Books and e-References - - 25
1. INTRODUCTION
Till now, you have learnt various components of JavaScript. Maybe you have started writing
simple functions with JavaScript. But in this unit, you will be introduced to a new feature of
JavaScript, i.e., object-oriented paradigm. Though JavaScript was started with simple one-
liners embedded in HTML, it is now used more sophisticatedly. The object-oriented
JavaScript approach offers reusability, scalability, and flexibility to your applications, which
minimises the duplication of code in your application. Before diving into the details of
JavaScript, you should know about the exact meaning of object-oriented programming.
Basically, as the name suggests, OOP puts objects at the centre of the programming model.
The object is probably the most important concept in the world of OOP – a self-contained
entity that has state and behaviour, just like a real-world object.
By now, you have learnt that in AJAX applications, client/server communication is packed in
XML documents. You will be introduced to another format in which client/server
communication can be packed, i.e., JSON (JavaScript Object Notation). It is a lightweight data-
interchange format that is easy for humans to read and write and easy for machines to parse
and generate.
This unit familiarises us with the object-oriented feature of JavaScript. Then MVC design
pattern for web applications is discussed. In this unit, we will also understand the ajax web
application. The unit discusses several components of JSON like JSON syntax, parser and we
will also understand the concept of JSON data transfer between client-server autosuggest.
In case of processing the request asynchronously, delays can be avoided, and the user can
interact with the webpage for another task. In this, requests are processed in the background
and response are updated whenever it arrives on the client-side. It is also beneficial in
another way since if the response is delayed in case of the enormous size of the data, the user
might not realise it since it lets the user interact elsewhere on the webpage.
For example, in the above syntax, there are two ajax requests to request API. There is a
callback function attached to it for iterating through the response. Once both the AJAX
requests are finished, the callback function gets executed.
In another case where multiple objects are passed to $.when(), both calls returned by the
response are taken by it and construct new objects.
3. PROTOTYPE
JavaScript is a very important concept since JavaScript is often classified as having a
prototype-based object model. It is just a new concept but not difficult. Basically, this is
considered as the property of the function object. If you define a simple function, sum(), you
can access its properties as you would do with any other object.
Function sum(a,b) {
Return a+b;
}
Now consider the above function has some other properties like the length. So you can call
that property as shown below:
Output: 2
The prototype property is available to you as soon as you define the function. Its initial value
is an empty object. To see that in the output, you can type:
➢ typeof sum.prototype
Output: “object”
That empty Object can be enlarged with properties and methods in the following manner:
➢ sum.prototype = { };
In that case, the sum () function won’t be affected. If you call sum () as a constructor, they
will only be used. All the methods and properties you have added to the prototype are
available as soon as you create a new object using the constructor.
{
return ‘ The Book’ + this.category + ‘ ‘ + this.name; } }
Now, if you create a newbook object using the library () constructor, you will be able to
access all the methods and properties defined earlier.
➢ newbook.category
Output: AJAX
➢ newbook.whatBook;
So finally, remember the prototype is “live”. It means if you modify the objects of the
prototype at any time, you will see the changes.
Built-in constructor functions like Array, String, Function, even Object can be enhanced
through the prototype. This means that you can, for example, add new methods to the Array
prototype, and in this way, you can make them available to all arrays.
• DOM
• XHTML and CSS
• XML and XSLT
• XMLHttpRequest and
• JavaScript
for various purposes. There are various web applications developed using AJAX such as
Gmail, Google suggests and Google Maps.
Unit 8: AJAX – Object-Oriented JavaScript 6
DCA8241: Advanced Web Programming Manipal University Jaipur (MUJ)
4. OBJECT-ORIENTED XMLHTTPREQUEST
As we have already studied in the previous unit, in JavaScript, a built-in browser object is
used named XMLHttpRequest to make HTTP requests. XMLHttpRequest can handle and
operate on any data despite having XML in its name. The handling may be track progress,
upload/download files, and much more. Fetch is another modern method introduced that
somewhat deprecates XMLHttpRequest.
The main purpose of XMLHttpRequest is to communicate with the server, so before starting
the communication, you need to create the object. The XMLHttpRequest object uses
JavaScript to request the server and process the response by minimising the postback delays.
It can be called an API that JavaScript can use to transfer XML and other formats of data
between the server and client using HTTP. The XMLHttpRequest object plays an important
role in developing AJAX-style applications to implement responsive and dynamic web
applications.
First, you can create an XMLHttpRequest object using JavaScript before you can use it to send
requests and process responses. Since XMLHttpRequest is not a W3C standard, creating an
instance of XMLHttpRequest object requires a browser check. As mentioned above, Internet
Explorer implements XMLHttpRequest as an ActiveX object, and other browsers such as
Firefox, Safari, and Opera implement it as a native JavaScript object. Because of these
differences, the JavaScript code must contain logic to create an instance of XMLHttpRequest
using the ActiveX technique or using the native JavaScript object technique.
There are various methods used to handle the XMLHttpRequest object. They are given in the
following Table 1.
3. responseXML This property is used when the response from the server
is an XML file.
4. responseText This property is used when the response from the server
is a text file.
Self-Assessment Questions -1
1. To do multiple simultaneous asynchronous requests, we can use
_____________.
2. __________ is “live” which means if you modify the objects of the
prototype at any time, you will see the changes.
3. _____________ a way of advancing a web application by putting more
behaviour in the web browser.
4. XMLHttpRequest object is created using _______________ language.
5. MODEL-VIEW-CONTROL (MVC)
This is the most widely used design pattern by web developers. So to build the AJAX
component and applications MVC design pattern is followed as a guideline. The MVC pattern
is usually utilised in the context of the client and server with the View implemented on the
client, and the controller and certainly the model encapsulated on the server. However, when
we start dealing with AJAX-based applications, much of the three aspects of the MVC pattern
can be implemented on the client, except in most cases of Model persistence. Fig. 1 illustrates
an MVC-based design pattern.
As you can see in the image, the dark line represents what could be thought of as explicitly
coded method invocations. The dashed lines represent the method of invocation of objects.
Generally, the controller has explicit connections to both the model and view. It may have
access to particular methods, which can be called on view and model. On the other hand, the
View and Model should ideally have no connections to the Controller or the View,
respectively.
In general, the MVC pattern describes a method of abstracting the data storage and
maintenance (the Model), the data presentation and interface (the View), and the application
logic and data translation between the Model and View (the Controller). In web applications,
usually, the MVC pattern gets implemented in server-side scripting. In the client-side
application also the pattern works in the same way. Fig. 2 shows the MVC pattern for client-
side application:
MVC pattern keeps the database interaction separate from the event generation and decision
making. Let’s discuss each component of the MVC pattern in detail.
The Model
In a client-side application, if an MVC pattern is used, the model acts as an abstract, i.e.,
similar to the logical manager of the data. Based on the data, the decision is taken where to
put the data management logic. You do not want the users to have their browser seize up as
JavaScript parses through kilobytes of strings adjusting formatting or spell checking.
Actually, the Model just follows orders from the Controller. According to the controller’s
demands, the Model manages and serves data. The Model never interacts with the View. The
View may not even exist, or multiple views may exist. It just needs to handle data storage
and retrieval as efficiently as possible and offer as easy a programmatic interface as possible.
The View
It implements the presentation of the data. This layer is generally implemented between the
application and DOM layer to save development time. Designed with a View in mind, a client-
side application can use the existing DOM structure as its set of templates for the elements it
interacts with and creates. This keeps the actual page structure and designs out of the
• Presenting information to the user: This layer decides the form of the information. It
may be in the form of strings, time or date, or any decision.
• Collecting information from the user: It deals with input.
The Controller
Between the View and the Model, the Controller sorts out how it all fits together. The
Controller for the interface is built up in the Model and View sections, and it keeps track of
both objects. It accepts input from the user, calls the appropriate method in the Model, and
sends data to the View for presentation.
There are several ways to implement MVC architecture with AJAX. For example, you can
think of the model as being on the server, the browser as the view, and the JavaScript in the
browser as the controller.
Self-Assessment Questions -2
5. MVC stands for ___________________.
6. If an MVC pattern is used in a client-side application, then the model acts as an
abstract. (True/False)
7. In MVC pattern the __________ just follows orders from the Controller.
8. In MVC design pattern ____________ layer is generally implemented between the
application and DOM layer to save development time.
Each JSON object is represented as a list of property names and values contained in curly
braces. So now you will see the same XML message in JSON format:
As you can notice above, JSON format involves a fewer number of characters compared to
XML format. JSON uses JavaScript syntax for describing data objects, but JSON is still
language and platform-independent. JSON parsers and JSON libraries exist for many
different programming languages. The primary point to understand is that JSON uses the
identical syntax for creating objects that JavaScript does.
An example of JSON
Now convert this function into an object to access all those local variables from outside the
function as follows:
var person = function() {
this.name = “Richard Rutter”;
this.website = “http://claqnut.com/”
this.email = “[email protected]”;
};
Now name, website, and email are available as properties of person: person.name,
person.website, and person.email. So now the same object can be written like:
{ “person”:{
“name”: “Richard Rutter”,
“website”: “http://cleqnut.com/”,
“email”: [email protected]
}
}
The above representation is called object literal. When object literal is purely used to store
data, then it will be JSON.
After getting introduced to JSON now, you will learn about JSON syntax. JSON has six kinds
of values: objects, arrays, strings, numbers, Booleans, and special values. Boolean takes two
values: True and False, and the special value indicates Null. The JSON object is an unordered
container of name/value pairs. Where a name can be any string and a value can be any other
object or array. The JSON array is an ordered sequence of values. A value can be any JSON
value, including arrays and objects. Arrays are specified by using square brackets ([ and ]).
They can be created using a constructor, or the values can directly be assigned in square
brackets ([ and ]). The following is the array declaration using a constructor: Now see the
following array declaration:
Now items can be added into the array using square brackets and an index value that
indicates the position of the item in the array as shown below:
The same object can be created in a more efficient way using the array literal:
Although an array can be created using a constructor, as shown previously, JSON accepts
only the Array Literal Declaration Model:
Most languages have a feature that maps easily onto JSON arrays, such as an array, vector,
list, or sequence. Now objects are defined to store name /value price. As mentioned above,
one basic difference of an object with the array is name/value pairs of an object are enclosed
between curly braces ({and}).
As you can see in the above example, JSON strings are packed in double quotes. JSON uses \
character for escapement and also allows / character to be escaped so that JSON can be
embedded in HTML <scripts> tags.
HTML does not allow the sequence < / except to start the </script> tag. JSON allows < \ /,
which produces the same result but does not confuse HTML. JavaScript numbers are similar
to JSON numbers. A number can be an integer, real, and scientific.
Like XML validation using DTD or schema, lots of web tools are available to validate JSON
documents. A general function eval () is used to evaluate or parse any JavaScript data. It takes
a JSON response and converts it into a JavaScript object. But the problem with the eval ()
function is it runs the JSON response from the server without any security checks. If some
malicious organisation is able to tamper with your server’s response, you could end up
running some harmful code in your JavaScript. To avoid that, you can use an explicit JSON
parser to create objects and arrays from JSON text and vice versa. You can also use a JSON
parser available at www.json.org/json.js. The intended file can be copied and referenced to
your page in the head section:
While parsing that json.js file using above mention JSON parser, the toJSONString()function
is added to JavaScript object and array definitions. And the output will be as follows:
String : (“Name”: “HP”, “Model”: “5446 A”, “Make”: “2007”, “Price”: “$896.00”)
An object is similar to an array only difference is that you define the keys for the object.
You’re not limited to using only numeric indexes, and you can use friendlier keys, such as
first_name, age, and so on.
Type: ‘senior’ ,
Department: ‘Developer’
};
The keys (names of the properties) can optionally be placed in quotation marks. For example,
these are all the same:
Use of quote is not mandatory for the name of properties, but sometimes it is required. Like
if the property name is similar to any of the JavaScript reserved words or the name consists
of a special character or starts with a number.
Here remember, defining an array with [] is called array literal notation, and defining an
object using the curly braces {} is called object literal notation.
As you know, a method is just a property that happens to be a function. So, like other
properties of an object, the method also can be accessed in the same way. Just use the method
name followed by parentheses and execute. See the following example:
var employee = {
Type: ‘senior’,
Department: ‘Developer’,
Say: function () {
};
Output: employee.say()
“I am Developer”
You already became familiar with the built-in objects in the previous unit. These objects can
be categorised into three groups:
• Data wrapper objects: these are objects mentioned as different data types in
JavaScript. Object, Array, Function, Boolean, Number, String are data wrapper objects.
• Utility objects: Math, Date, and RegExp fall into this group.
• Error objects: These include the generic Error object as well as other more specific
objects that can help your program recover its working state when something
unexpected happens.
Self-Assessment Questions -3
9. JSON stands for _____________________.
10. What is JSON?
11. JSON is language dependent. (True/False)
12. What is the purpose of eval() function?
13. ____________ converts the JSON text into a JavaSCript object.
7. SUMMARY
• JavaScript is an object-based language, but it isn’t generally considered a fully object-
oriented language because it lacks support for some features that you’d find in “real”
OOP languages or simply implements them differently. Few essential concepts in OOPs
are Object, method, and property, Class, Encapsulation, Aggregation, Reusability/
inheritance, and Polymorphism.
• An object represents a “thing”, and this representation is expressed with the help of a
programming language. An object is an instance of a class (also called type).
Encapsulation is a concept that allows the use of an object without knowing a concept
that will enable the use of an object without knowing its internal implementation in
detail. Aggregation is combining several objects into a single and new one. Inheritance
allows creating classes that are specialised versions of an existing class. Polymorphism
allows using objects of different classes when you only know the common base class
from which they both derive.
• A prototype is considered as the property of the function object. The prototype
property is available to you as soon as you define the function. Its initial value is an
empty object. Built-in constructor functions like Array, String, Function, even Object
can be enhanced through the prototype.
• The MVC pattern is usually utilised in the context of the client and server with the View
implemented on the client, and the Controller and certainly the Model encapsulated on
the server. MVC pattern describes a method of abstracting the data storage and
maintenance (the Model), the data presentation and interface (the View), and the
application logic and data translation between the Model and View (the Controller).
• JavaScript Object Notation (JSON) is an alternative to XML for representing data. JSON
is a text-based data-interchange format used to represent objects in JavaScript as
collections of name/value pairs represented as strings. It’s commonly used in AJAX
applications.
8. GLOSSARY
• Prototype: A prototype is an object instance. It allows you to define methods to all
instances of a particular object easily.
• Parser: It is a compiler used to break the data into smaller elements.
• Literals: In JavaScript, literals are syntactic representations of different data types.
• Constructor: A constructor is a function, which creates an instance of a class known as
an object.
• Vector: A vector in javascript is a type of array whose size is not fixed.
9. TERMINAL QUESTIONS
SHORT ANSWER QUESTIONS:
Q2. Explain the MVC design pattern for the web application.
Q3. Define JSON. Convert a JavaScript example into an object and create a JSON document
for that example.
1. jQuery.when()
2. prototype
3. AJAX
4. JavaScript
5. Model View Controller
6. True
7. Model
8. View
9. JavaScript Object Notation
10. JavaScript Object Notation (JSON) is an alternative to XML for representing data. JSON
is a text-based data-interchange format used to represent objects in JavaScript as
collections of name/value pairs represented as strings.
11. False, since JSON is language-independent.
12. A general function eval () is used to evaluate or parse any JavaScript data.
13. ParseJSON( )
TERMINAL QUESTIONS
Answer 2: The prototype is a very important concept of JavaScript since JavaScript is often
classified as having a prototype-based object model. It is just a new concept but not difficult.
Basically, this is considered as the property of the function object.
Answer 1: The main purpose of XMLHttpRequest is to communicate with the server so,
before starting the communication, you need to create the object. The XMLHttpRequest
object uses JavaScript to request the server and process the response by minimising the
postback delays.
Answer 2: MVC is the most widely used design pattern by web developers. So to build the
AJAX component and applications Model View Controller (MVC) design pattern is followed
as a guideline. The MVC pattern is usually utilised in the context of the client and server with
the View implemented on the client, and the Controller and certainly the Model encapsulated
on the server.
Answer 3: JavaScript Object Notation (JSON) is an alternative to XML for representing data
JSON. It is a simple format that makes objects easy to read, create and parse, and allows
programs to transmit data efficiently across the Internet is much less verbose than XML.
• Jamsa, K. A., King, K., & Anderson, S. F. (2002). HTML & Web Design: Tips & Techniques.
New York, NY: McGraw-Hill/Osborne.
• FLANAGAN, D. (2020). Javascript: The Definitive Guide. Sebastopol, CA: OREILLY MEDIA,
INC, USA.
• Object-Oriented Javascript. (2011).
REFERENCES: