0% found this document useful (0 votes)
3 views144 pages

Module 5 Reference Material II

Client-server communication is a fundamental architecture in computer networks where clients request services from servers, which process and respond to these requests. The communication follows a request-response model, utilizing protocols like HTTP for web interactions, and is essential for various applications such as web browsing, mobile apps, and online transactions. Key features of HTTP include its request methods (GET, POST), response status codes, and the ability to handle persistent connections and cookies for user sessions.

Uploaded by

lifewithvndv
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)
3 views144 pages

Module 5 Reference Material II

Client-server communication is a fundamental architecture in computer networks where clients request services from servers, which process and respond to these requests. The communication follows a request-response model, utilizing protocols like HTTP for web interactions, and is essential for various applications such as web browsing, mobile apps, and online transactions. Key features of HTTP include its request methods (GET, POST), response status codes, and the ability to handle persistent connections and cookies for user sessions.

Uploaded by

lifewithvndv
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

Client-Server Communication: HTTP

Dr. Hiteshwar Kumar Azad


Email ID: [Link]@[Link]
SCOPE
Client-Server communication
• Client-server communication is the fundamental architecture used in computer networks
where clients request services or resources, and servers process and respond to these
requests.
• Used in web browsing, email, databases, and various network applications.
In a client-server architecture:
• Client: The device or application that initiates a request
(e.g., web browsers, mobile apps).
• Server: The machine or system that processes the
request and sends back a response (e.g., web servers,
database servers).
Basic Communication Flow
1. The client sends a request to the server.
2. The server processes the request.
3. The server sends a response back to the client.
4. The client processes and displays the response.
2
Key Characteristics: Client-Server communication
• Request-Response:
• Communication follows a request-response pattern.
• The client sends a request, and the server sends a response.
• Requests: Requests are sent from the client in order to ask the server for some data
like files, or tell the server about things that happen, like that a user wants to login
with his credentials.
• Response: A response is sent from the server to the client and is the reaction of the
server to a request of the client. This could for example be an authentication result.
• Service: A Service is a specific task that the server provides for the client to use, like
downloading an image.
• Server Functions: Servers can provide various services, such as:
• Web services (serving web pages)
• File services (providing access to files)
• Database services (managing data)
• Protocols:
• Communication relies on protocols, which are sets of rules that define how data is
exchanged.
• Examples include HTTP (for web browsing), FTP (for file transfer), and SMTP (for email).
3
When we need client-server communication?
• Client-server communication is essential whenever a client (user device or
application) needs to interact with a server (centralized system) to access or
exchange data.
• This architecture is widely used in various scenarios, including web applications,
mobile apps, cloud computing, and real-time communication.
• Client-Server communication is always used, whenever someone requests something from
the internet.
• Examples: Facebook, Twitter, Instagram, Maps or games like Temple Run and so on.
• Access to remote data
Real-time updates
Secure transactions
Cloud storage
Multiplayer or collaborative features

13-03-2025 4
When Do We Need Client-Server Communication?
1️⃣ Accessing Web Applications & Websites
Browsing websites, filling forms, interacting with web pages.
2️⃣ Mobile App Communication with Servers
Fetching user profiles, product listings, or messages from a remote server.
3️⃣ Cloud Storage & File Sharing
Uploading, downloading, and sharing files across multiple devices.
4️⃣ Online Gaming & Multiplayer Games
Real-time interactions between players via a game server.
5️⃣ Messaging & Video Calling Apps
Sending messages, making calls, and participating in live chats.
6️⃣ E-Commerce & Online Transactions
Browsing products, adding to cart, and making secure payments.
7️⃣ Fetching & Storing Data in Databases
Retrieving banking transactions, employee data, or user information.
8️⃣ IoT (Internet of Things) Devices & Smart Homes
Sending sensor data and receiving commands for automation.
9️⃣ Streaming Services (Video & Audio)
Watching Netflix, YouTube, or listening to Spotify.
Software Updates & API Communication
Downloading app updates and communicating with external services.
Protocols for Client-Server Communication
• Several protocols enable communication between clients and servers.
Some common ones include:
• HTTP/HTTPS (Hypertext Transfer Protocol)
• Used for web communication between browsers and web servers.
• HTTPS is a secure version of HTTP using SSL/TLS encryption.
• Works on a request-response model.

6
HyperText Transfer Protocol
• Invented by Tim Berners-Lee at CERN in the years 1989–1991, HTTP (Hypertext
Transfer Protocol) is the underlying communication protocol of World Wide Web.
• HTTP functions as a request–response protocol in the client–server computing
model.

PC running
Chrome
• Client/server model
• Client: browser that requests,
receives, displays Web objects
Web Server
• Server: Web server sends objects in e.g., Apache HTTP
response to requests server, nginx, etc.

Mac running
Safari 7
HTTP Overview

• Client-Server Model:
• Client: A browser or application that requests, receives, and displays web objects.
• Server: A web server that processes requests and sends responses.
• HTTP Versions:
• Clients and servers may use different HTTP versions (e.g., HTTP/1.1, HTTP/2, HTTP/3).
• Both must specify the HTTP version in the first line of their message.
• RFC (Request for Comments):
• Defines the rules and actions for client-server communication.
• Ensures compatibility across different HTTP versions.

13-03-2025 8
HTTP (Hyper Text Transfer Protocol)
• HTTP is an application-layer protocol for distributed, hypermedia systems.
• Purpose: It is a data communication protocol that enables interaction between clients
(browsers) and servers.
• TCP/IP-based Communication:
• Function: HTTP operates over TCP/IP.
• Default port: TCP 80 (for unencrypted communication).
• Function:
• Delivers web resources like HTML files, images, and query results over the World Wide Web
(WWW).
• Uses a request-response model (Client sends an HTTP request → Server responds).
• Standardization: Provides a universal way for computers to communicate on the
internet.

13-03-2025 9
Basic Features of HTTP

10
Basic Architecture of HTTP

• HTTP is request/response protocol


which is based on client/server based
architecture.
• In this protocol, web browser, search
engines, etc. behave as HTTP clients
and the Web server like Servlet
behaves as a server.

13-03-2025 11
HTTP Messages

12
Structure of an HTTP Message
HTTP requests (sent by a client) and HTTP responses (sent by a server) follow a
similar format and consist of the following components:

13-03-2025 13
Structure of an HTTP Message
HTTP requests (sent by a client) and HTTP responses (sent by a server) follow a
similar format and consist of the following components:

13-03-2025 14
HTTP requests and responses

15
HTTP Requests
• The request sent by the computer to a web server, contains all sorts of potentially
interesting information; it is known as HTTP requests.
• The HTTP client sends the request to the server in the form of request message which
includes following information:
• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Requested URI (Uniform Resource Identifier)
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header

16
HTTP request methods
HTTP Request Description
GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET
request with extra info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just
like GET but with no body.

TRACE Asks for the loopback of the request message, for testing or
troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request
URL can respond
13-03-2025 17
Get vs. Post
GET POST
In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data can be sent because data is sent in
data is sent in header. body.
Get request is not secured because data Post request is secured because data is
is exposed in URL bar. not exposed in URL bar.

Get request can be bookmarked. Post request cannot be bookmarked.

Get request is idempotent . It means Post request is non-idempotent.


second request will be ignored until
response of first request is delivered
Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.
13-03-2025 18
Difference between POST and PUT
POST PUT
POST: the URL of the request identifies PUT: the URL of the request identifies
the resource that processes the entity the resource that is contained in the
body. entity body.

13-03-2025 19
Difference between HEAD and GET
GET HEAD
GET: return the requested resource in HEAD: return all the response headers
the entity body of the response along in the GET response, but without the
with response headers (we’ll see these resource in the entity body
shortly)

13-03-2025 20
GET and POST
• Two common methods for the request-response between a server and client are:
• GET- It requests the data from a specified resource
• POST- It submits the processed data to a specified resource

13-03-2025 21
Uploading form input: GET and POST

POST method: GET method:


• Web page often includes form input • Entity body is empty
• Input is uploaded to server in entity body • Input is uploaded in URL field of request
line
• Posted content not visible in the URL • Example:
• Free form content (ex: images) can be posted • [Link]
since entity body interpreted as data bytes

13-03-2025 22
Anatomy of Get Request
• The query string (name/value pairs) is sent inside the URL of a GET request:
GET/[Link]?name1=value1&name2=value2
Here, name1=value1 and name2=value2 are query parameters that the client sends to the server.
• Data is sent in request header in case of get request. It is the default request type. The
following information is sent to the server.

13-03-2025 23
Anatomy of Get Request
Features of GET Requests:
[Link] remains in the browser history
1. Since GET requests send data in the URL, they are stored in the browser's history, making them easy to
revisit.
[Link] can be bookmarked
1. Users can save a GET request URL as a bookmark and return to it later.
[Link] can be cached
1. Browsers and servers can store GET request responses, improving performance by reducing redundant
requests.
[Link] has length restrictions
1. URLs have a size limit (usually around 2048 characters in most browsers), restricting the amount of data a
GET request can send.
[Link] should never be used when dealing with sensitive data
1. Since GET parameters are visible in the URL, they should not be used for passwords, credit card details, or
other sensitive information.
[Link] should only be used for retrieving data
1. GET requests are meant for reading data, not modifying it. If you need to update, delete, or add data, use
POST, PUT, or DELETE requests.
Features of GET Requests
Key Characteristics of GET:
[Link] in Browser History – The URL (including query parameters) can be
saved and revisited.
[Link] be Bookmarked – Since the URL contains all necessary information,
users can bookmark it.
[Link] be Cached – Browsers and proxies can store GET responses, improving
speed.
[Link] Restrictions – URLs have a length limit (around 2048 characters in
most browsers).
[Link] Secure for Sensitive Data – Since the data is in the URL, it can be
logged and intercepted.
[Link] for Retrieving Data – GET requests should only be used for reading
information, not modifying it.

13-03-2025 25
Anatomy of Post Request
• The query string (name/value pairs) is sent in HTTP message body for a POST request:
POST/[Link] HTTP/1.1
Host: www. [Link]
name1=value1&name2=value2
The parameters (name1=value1&name2=value2) are hidden inside the request body.
Security Advantage
• POST is safer because data is not stored in browser history or visible in URLs.
• Used for sensitive operations, such as login forms, user registrations, and payments.

26
• Some other features of POST requests are:
This requests cannot be bookmarked
This requests have no restrictions on length of data
This requests are never cached
This requests do not retain in the browser history
13-03-2025 27
HTTP response status codes
HTTP response status codes indicate the outcome of a client’s request to a server. In
first line in server->client response message. A few sample codes:
200 OK
• request succeeded, requested object later in this message
301 Moved Permanently
• requested object moved, new location specified later in this message (Location:)
403 Forbidden
• Insufficient permissions to access the resource
404 Not Found
• requested document not found on this server
505 HTTP Version Not Supported How HTTP Status Codes Are Used
•200 OK → When a webpage loads successfully.
•404 Not Found → When a user visits a non-existing webpage.
•500 Internal Server Error → When a website crashes due to
13-03-2025 28
server issues.
Try sending a HTTP request yourself!

Connect to a Web Server Using Telnet


•This opens a TCP connection to [Link] on port 80,
1. Telnet to your favorite Web server: which is the default port for HTTP.
telnet [Link] 80 •Any text typed after this is sent directly to the web
server.

Send a GET Request


•GET / HTTP/1.1 → Requests the homepage (/) using HTTP
2. Type in a GET HTTP request: version 1.1.
•Host: [Link] → Specifies the target host, which is
GET / HTTP/1.1 required for HTTP/1.1.
Host: [Link] •Important: You need to press the Enter key twice to send
the request.

View the HTTP Response


•Once the request is sent, the HTTP server responds with an
HTTP response message.
3. Look at response message sent by HTTP server! •The response may include:
•An HTTP status code (e.g., 200 OK, 404 Not Found).
13-03-2025 •Headers (e.g., Content-Type, Date).
•The requested webpage content (HTML source code).
Additional details about HTTP
1️⃣ Persistent vs. Nonpersistent HTTP Connections
•Persistent Connection:
•Uses a single TCP connection for multiple HTTP requests/responses.
•Reduces latency since a new connection doesn’t need to be created for each request.
•Enabled by default in HTTP/1.1 (using Connection: keep-alive header).
•Nonpersistent Connection:
•A new TCP connection is established for each request-response cycle.
•Causes higher overhead due to repeated connection setups.
•Default behavior in HTTP/1.0 unless explicitly set to persistent.
2️⃣ Cookies (User-Server State)
•Definition: Small pieces of data stored on the client’s browser, sent to the server with each request.
•Use Cases:
•User authentication (staying logged in).
•Session tracking (shopping carts, preferences).
•Personalized experiences (ads, recommendations).
•Set by the Server:
The server includes a Set-Cookie header in the response.
13-03-2025 30
Additional details about HTTP
3️⃣ Web Caches
•What is Web Caching?
•Temporarily stores copies of frequently accessed web resources (HTML, images, CSS,
JavaScript).
•Reduces load times and bandwidth usage.
•Types of Web Caches:
•Browser Cache: Stores local copies of web pages.
•Proxy Cache: Used in networks (e.g., company networks) to reduce traffic.
•Content Delivery Network (CDN): Global servers that cache web content closer to users.
•Controlled using HTTP Headers:
•Cache-Control, Expires, ETag help manage caching behavior.

13-03-2025 31
HTTP connections
Non-persistent HTTP (Used in HTTP/1.0) Persistent HTTP (Used in HTTP/1.1 by Default)
• Each TCP connection can only send one • A single TCP connection can be used for
object (e.g., an image, HTML file, CSS file). multiple objects.
• After sending one object, the connection • Reduces latency by avoiding repeated
closes, and a new connection must be connection setups.
established for the next request. • More efficient for loading web pages with
• Leads to higher overhead due to repeated multiple resources.
TCP connection setups.

TCP as the Underlying Transport Layer


• Both non-persistent and persistent HTTP use TCP for reliable data transfer.
• TCP ensures that a connection is established before data is sent.
• TCP handles packet loss, retransmissions, and flow control for reliable communication.

Key Takeaway:
• Persistent connections are more efficient than non-persistent connections because they reduce the time
spent on establishing new TCP connections. 32
Non-persistent HTTP

1a. HTTP client initiates TCP connection


to HTTP server 1b. HTTP server at host “accepts”
connection, notifying client
Suppose user visits
a page with text
2. HTTP client sends HTTP
and 10 images. request message 3. HTTP server receives request
message, replies with response
message containing requested
object
5. HTTP client receives response
message containing html file, 4. HTTP server closes TCP
displays html. Parsing html file, connection.
finds 10 referenced jpeg objects
time
6. Steps 1-5 repeated for each of
10 jpeg objects
Non-Persistent HTTP’s Response time
Round Trip Time (RTT): time to send a packet from client
to server and back.
• Sum of propagation, transmission, and queueing delays
along both directions.
Response time:
• One RTT to initiate TCP connection
initiate TCP
• One RTT for HTTP request and first few bytes of HTTP connection
response to return RTT
• File transmission time request
file
total = 2RTT + file transmission time time to
RTT
transmit
Key Takeaways file
file
•Each object request requires a separate TCP connection, adding extra received
RTTs.
•If a webpage contains multiple objects (e.g., images, scripts, stylesheets), time time
the delays multiply, making loading slower.
•This inefficiency is why Persistent HTTP (used in HTTP/1.1) improves 34
Persistent HTTP: jumping to steps 4/5

4. HTTP server sends a response.


Server keeps the TCP
5. HTTP client receives response
message containing html file, connection alive.
displays html. Parsing html file,
finds 10 referenced jpeg objects

time
The 10 objects can be requested over the same
TCP connection.
i.e., save an RTT trying to open a new TCP
connection per object.
35
Persistent vs. Non-persistent
Non-persistent HTTP requires at least 2 RTTs per object.
• For each object: Open TCP connection; send HTTP request & receive response

Persistent HTTP: since server leaves connection open after sending response,
subsequent HTTP messages between same client/server sent over the open
connection
Save one RTT per object relative to non-persistent HTTP

In both cases, browsers have a choice of opening multiple parallel connections.


Why Persistent HTTP is Better
Reduces connection setup overhead
Allows multiple requests over a single connection
Supports HTTP pipelining (faster request handling)
Default mode in HTTP/1.1 and later
36
Persistent and Non-Persistent Connections
Persistent HTTP Non-Persistent HTTP

The server leaves the connection open


Requires 2 RTTs per object.
after sending a response.
Subsequent HTTP messages between the
same client/server are sent over an open OS overhead for each TCP connection
connection.
The client sends requests as soon as it Browsers often open parallel TCP
encounters a referenced object. connections to fetch referenced objects.
As little as one RTT for all the referenced Here, at most one object can be sent over
objects. one TCP Connection.

13-03-2025 37
HTTP: User data on servers?
So far, HTTP is “stateless”
• The server maintains no memory about past client requests

But state, i.e., memory, about the user at the server is very useful!
• authorization
• shopping carts
• recommendations
• In general, user session state

38
HTTP overview

39
HTTP Cookies

What is a cookie?

• Cookie in simpler terms means just the textual information about some website.
• you visit a particular website, some information is saved in your local system so
that when you visit the same website again, this website is able to recognize you
and show you the results according to your preferences.
• Cookies have been long used in the internet history and have developed in a
magnificent way.

13-03-2025 40
Why to use cookies?
• Let say you visit a website which is not in your local language (let’s say English).
• You choose the English option in the language section of the website. Now if you
visit the same website 5 times a day, you might have to change the language 5
times.
• Therefore, this information is saved as a cookie in your system. So the next time
you send the request, the server will know that you want to see the website in
English.
• This is where cookies play a vital role.

13-03-2025 41
Advancement of cookies:
• Today, cookies are used from what you searched to even what you saved in your
cart. Cookies are used today at an extreme level saving your information about
various websites.
• Knowing this, it is obvious that the size of the information has increased.
• So developers have recognized that all the information cannot be saved in the
client’s machine as it will increase the cookie size which is sent with requests and
also will load the client’s machine.
• Now, if you visit a website, the website provide you with a cookie id which is
uniquely recognizable by the server. This id is then linked to the database of the
company where all your information is saved and then fetched from the
database.
• This way cookies can be managed more efficiently and more securely.

13-03-2025 42
Using HTTP cookies

• An HTTP cookie (web cookie, browser cookie) is a small piece of data that a
server sends to a user's web browser.
• The browser may store the cookie and send it back to the same server with later
requests.
• Typically, an HTTP cookie is used to tell if two requests come from the same
browser—keeping a user logged in, for example.
• It remembers stateful information for the stateless HTTP protocol.

13-03-2025 43
Cookies are mainly used for three purposes:
• Session management
Logins, shopping carts, game scores, or anything else the server should remember
• Personalization
User preferences, themes, and other settings
• Tracking
Recording and analyzing user behavior

13-03-2025 44
The lifetime of a cookie can be defined in two ways:

•Session cookies are deleted when the current session ends. The browser defines when

the "current session" ends, and some browsers use session restoring when restarting.

This can cause session cookies to last indefinitely.

•Permanent cookies are deleted at a date specified by the Expires attribute, or after a

period of time specified by the Max-Age attribute.

13-03-2025 45
Security threats related to Cookies
• Cookies as you must have come to know till now, saves your information to your
machine. This information is highly personal to you and should only be retrieved
by the server which saved it. Does it possess any security threats? Fortunately no.
• A cookie cannot be used by any other server as the id saved in your cookie is
directly mapped to the website’s database.
• A cookie can never be used to access any information saved in your system,
browser or hard disk.
• A cookie cannot be used to deliver viruses or any other threats.
• A cookie but can be used by a third website (with permissions of course) to
access the information and/or your preferences to use them for their and
your benefit.

13-03-2025 46
Web caches
Web caches: Machines that remember web responses for a network

Why cache web responses?

• Reduce response time for client requests

• Reduce traffic on an institution’s access link

Caches can be implemented in the form of a proxy server

47
How a web cache works

• Whenever content is downloaded from the origin server, a copy is stored in the
web cache for a set period of time determined by caching rules you set.
• If another user requests the same content again, the web cache sends the stored
content and the user request does not have to be forwarded to origin server
again. This is known as content caching.

13-03-2025 48
• A typical web cache flow looks like this:
1.A user accesses a website.
[Link] browser sends an HTTP request to the web cache.
[Link] the requested object IS stored in the cache, the web cache responds with the
object. If the requested object IS NOT stored in the cache, the web cache
requests the object from the origin server and sends the response to the browser.
[Link] the object is cacheable, the web cache retains a copy of the object so that
subsequent requests are served locally from the web cache.

13-03-2025 49
Example of a web cache
• Teachers and students of Harare International School (HIS) needed fast internet
to research and communicate effectively. But they were challenged by the
expensive and limited bandwidth for the school’s 700+ connected devices. At
$6000 per month for an 8Mbps internet connection, the school ruled out a
bandwidth upgrade. Instead, they opted for a web caching solution.
• The web cache appliance was used in conjunction with a Cisco router. The router
redirects the web traffic while the device keeps a copy of all videos, images, and
other static content. Caching the content enabled the school to have significant
improvements in web performance without spending more on bandwidth. This
was especially useful during back-to-back group lessons when students had to
access the same content.

13-03-2025 50
4 types of Web Cache
1. Site Cache
2. Browser Cache
3. Server Cache
4. Micro Cache

13-03-2025 51
Site Cache
• A site cache or page cache stores website data the first time a webpage is loaded.
Each time a user returns to your website, saved elements are quickly accessed
and displayed to visitors.
• This is a type of client-side caching, which means that all the stored elements are
controlled by the end-user. As a website owner, your only say is how long content
remains in the cache.
• If a page has elements that never change, you can set the cache expiration date
far into the future. However, elements that change regularly should have shorter
expiration periods, so they’re periodically refreshed. Otherwise, your site will
continue to display outdated content to users loading it from their site caches,
even after you’ve published updates.
• For this reason, site caching is ideal for websites with a lot of static content.

13-03-2025 52
Site Cache
• Finally, there are two more situations where implementing a site cache can be
beneficial:
• High-traffic sites: if your site receives a lot of traffic, a site cache can help
reduce the server load and improve the site’s performance.
• Dynamic sites: dynamic sites, which generate content on the fly in response
to user requests, can benefit from caching as it can help to reduce the
amount of processing required to generate each page.

13-03-2025 53
Browser cache
• Browser caching is a type of site caching built into the end-user’s web browser.
• A browser cache can contain HTML pages, CSS stylesheets, images, and other
multimedia content. Website elements are stored by the browser on your
visitor’s computer and grouped with other files associated with your content.
• Browser caching overlaps with site caching because they are both client-side
systems.
• The primary difference is that the browser controls the cache rather than the
end-user. All browsers have a cache that flushes out old files without any need
for user intervention.

13-03-2025 54
Browser cache
• When is it advisable to use Browser caching
• Sites with static content: sites with static content that do not frequently
change, such as an online brochure or portfolio, can benefit from browser
caching as it can reduce the amount of data that needs to be transferred over
the network on each request.
• Sites with considerable resources: sites with large resources, such as high-
resolution images or video files, can benefit from browser caching as it can
reduce the time needed to download these resources on subsequent visits.
• Sites with a high number of returning visitors: if your site has a high number of
returning visitors, browser caching can help improve the site’s performance for
these users as they will not need to download the same resources on each visit.

13-03-2025 55
Server cache
• Server cache is an umbrella term covering several different types of caching. This
includes Content Delivery Network (CDN) caching, object caching, and opcode
caching. Each stores different content on your website’s server. This type of
caching is administered by website owners without end-users’ input.
• Server caching is one of the best methods for reducing server loads. It improves
the performance and scalability of a website. When a request is made, the server
checks its temporary storage for the necessary content before processing it the
request in full. If the requested content is available in the server cache, it will be
returned to the browser right away. This enables your server to handle more
traffic and return your webpages faster.

13-03-2025 56
Micro cache

• Another type of caching that many website owners might not be aware of is
micro caching. This method stores content for very short periods of time. It
generally saves static versions of dynamic elements for up to 10 seconds. As this
is a type of site cache, it’s controlled by end-users with limited input from website
owners.
• Micro caching is not a common type of cache because of the short storage time.
The sites that benefit from this form of caching also fit into a small profile.
They’re typically high traffic and feature rapidly changing content, such as the
constantly updating graphs on currency exchange and stock websites.

13-03-2025 57
• Benefits of micro cache include:
• Improved performance: by storing frequently requested data in a cache, you can reduce the
server load and improve your site’s performance.
• Reduced server load: micro caching helps reduce the load on your server by reducing the
number of requests that need to be processed.
• Improved scalability: by offloading some of the processing to the cache, you can improve the
scalability of your site and handle more traffic without needing to add additional servers.

13-03-2025 58
Summary
• Client-side and server-side caching both have their benefits. They also have
different implementation methods. Choosing the right type of web cache can
boost your page loading speeds and improve your site’s User Experience (UX).
• When choosing the right type of web cache, there are four options you need to
know about:
[Link] cache: Ideal for static content, (presentational websites, etc)
[Link] cache: A popular and effective client-side cache option.
[Link] cache: Best for high-traffic websites that need to reduce server strain.
[Link] cache: A targeted option for highly dynamic sites.

13-03-2025 59
Web caching using a proxy server
• You can configure a HTTP proxy
on your laptop’s network settings.
Clients • If you do, your browser sends all
HTTP requests to the proxy
(cache).
Web Server • Hit: cache returns object
GET [Link] (also called • Miss:
GET [Link] origin server in • cache requests object from origin
this context)
server
• caches it locally
Proxy
Server The Internet • and returns it to client

Store [Link]
on receiving
response 60
Web Caches: how does it look on HTTP?
cache server
• Conditional GET guarantees HTTP request msg
cache content is up-to-date If-modified-since:
object
<date>
while still saves traffic and not
response time whenever modified
HTTP response
possible HTTP/1.0
304 Not Modified

• Date in the cache’s request is


HTTP request msg
the last time the server If-modified-since:
provided in its response <date> object
header “last modified” modified
HTTP response
HTTP/1.0 200 OK
<data>
[Link] - SCOPE VIT VLR 61
Without CDN DOMAIN NAME IP ADDRESS
[Link] [Link]
[Link] [Link]
[Link] [Link]
[Link] [Link]

Cluster with Rutgers CS


origin servers

• Huge bandwidth requirements for Rutgers [Link]

• Large propagation delays to reach users


• So, distribute content to geographically distributed cache servers.
• Often, use DNS to redirect request to users to copies of content
62
CDN terms
• Origin server
• Server that holds the authoritative copy of the content
• CDN server
• A replica server owned by the CDN provider
• CDN name server
• A DNS like name server used for redirection
• Client

63
DOMAIN NAME IP ADDRESS
[Link] [Link]

With CDN [Link]


[Link]
[Link] (NS of CDN)
[Link]
[Link] [Link]
Implement DNS delegation
to the CDN name server. CDN Name Server ([Link])
Custom logic
“layer of indirection” DOMAIN NAME IP ADDRESS
to map ONE
[Link] [Link]
domain
[Link] [Link]
[Link] [Link]
name to one
[Link] [Link]
of many IP
addresses!

[Link]
CDN servers [Link]

[Link] [Link]
[Link]
Origin server

Client Most requests go to CDN servers (caches).


Only the remainder go to the origin server. 64
What is an API?
• An application programming interface (API) defines the rules that you must
follow to communicate with other software systems.
• Developers expose or create APIs so that other applications can
communicate with their applications programmatically.
• For example, the timesheet application exposes an API that asks for an
employee's full name and a range of dates.
• When it receives this information, it internally processes the employee's
timesheet and returns the number of hours worked in that date range.
• You can think of a web API as a gateway between clients and resources on
the web.

3/13/2025 65
What is REST?
• Representational State Transfer (REST) is a software architecture that imposes
conditions on how an API should work.
• REST was initially created as a guideline to manage communication on a complex
network like the internet.
• REST-based architecture can be used to support high-performing and reliable
communication.
• API developers can design APIs using several different architectures. APIs that
follow the REST architectural style are called REST APIs.
• Web services that implement REST architecture are called RESTful web services.
• The terms REST API and RESTful API interchangeably.

13-03-2025 66
In order for an API to be considered RESTful, it has to conform to these criteria:
• A client-server architecture made up of clients, servers, and resources, with
requests managed through HTTP.
• Stateless client-server communication, meaning no client information is stored
between get requests and each request is separate and unconnected.
• Cacheable data that streamlines client-server interactions.
• A uniform interface between components so that information is transferred in a
standard form. This requires that:
• resources requested are identifiable and separate from the representations
sent to the client.
• resources can be manipulated by the client via the representation they
receive because the representation contains enough information to do so.
• self-descriptive messages returned to the client have enough information to
describe how the client should process it.
• hypertext/hypermedia is available, meaning that after accessing a
resource the client should be able to use hyperlinks to find all other currently
available actions they can take.
13-03-2025 67
• A layered system that organizes each type of server (those responsible for
security, load-balancing, etc.) involved the retrieval of requested information into
hierarchies, invisible to the client.
• Code-on-demand (optional): the ability to send executable code from the server
to the client when requested, extending client functionality.
• Though the REST API has these criteria to conform to, it is still considered easier
to use than a prescribed protocol like SOAP (Simple Object Access Protocol),
which has specific requirements like XML messaging, and built-in security and
transaction compliance that make it slower and heavier.

13-03-2025 68
What are the benefits of RESTful APIs?

• Scalability
• Systems that implement REST APIs can scale efficiently because REST
optimizes client-server interactions.
• Statelessness removes server load because the server does not have to retain
past client request information.
• Well-managed caching partially or completely eliminates some client-server
interactions.
• All these features support scalability without causing communication
bottlenecks that reduce performance.

13-03-2025 69
What are the benefits of RESTful APIs?

• Flexibility
• RESTful web services support total client-server separation.
• They simplify and decouple various server components so that each part can
evolve independently.
• Platform or technology changes at the server application do not affect the
client application.
• The ability to layer application functions increases flexibility even further.
• For example, developers can make changes to the database layer without
rewriting the application logic.

13-03-2025 70
What are the benefits of RESTful APIs?

• Independence
• REST APIs are independent of the technology used.
• We can write both client and server applications in various programming
languages without affecting the API design.
• We can also change the underlying technology on either side without
affecting the communication.

13-03-2025 71
What does the RESTful API client request contain?
• RESTful APIs require requests to contain the following main components:
• Unique resource identifier
• The server identifies each resource with unique resource identifiers. For REST
services, the server typically performs resource identification by using a Uniform
Resource Locator (URL). The URL specifies the path to the resource. A URL is similar
to the website address that you enter into your browser to visit any webpage. The
URL is also called the request endpoint and clearly specifies to the server what the
client requires.
• Method
• Developers often implement RESTful APIs by using the Hypertext Transfer Protocol
(HTTP). An HTTP method tells the server what it needs to do to the resource. The
following are four common HTTP methods:
• GET
• Clients use GET to access resources that are located at the specified URL on the
server. They can cache GET requests and send parameters in the RESTful API request
to instruct the server to filter data before sending.

13-03-2025 72
What does the RESTful API client request contain?
• POST
• Clients use POST to send data to the server. They include the data representation with the
request. Sending the same POST request multiple times has the side effect of creating the
same resource multiple times.
• PUT
• Clients use PUT to update existing resources on the server. Unlike POST, sending the same
PUT request multiple times in a RESTful web service gives the same result.
• DELETE
• Clients use the DELETE request to remove the resource. A DELETE request can change the
server state. However, if the user does not have appropriate authentication, the request fails.
• HTTP headers
• Request headers are the metadata exchanged between the client and server. For instance,
the request header indicates the format of the request and response, provides information
about request status, and so on.

13-03-2025 73
What does the RESTful API client request contain?
• Data
• REST API requests might include data for the POST, PUT, and other HTTP
methods to work successfully.
• Parameters
• RESTful API requests can include parameters that give the server more details
about what needs to be done. The following are some different types of
parameters:
• Path parameters that specify URL details.
• Query parameters that request more information about the resource.
• Cookie parameters that authenticate clients quickly.

13-03-2025 74
What are RESTful API authentication methods?
• A RESTful web service must authenticate requests before it can send a response.
Authentication is the process of verifying an identity. For example, you can prove
your identity by showing an ID card or driver's license. Similarly, RESTful service
clients must prove their identity to the server to establish trust.
• RESTful API has four common authentication methods:
• HTTP authentication
• HTTP defines some authentication schemes that you can use directly when
you are implementing REST API. The following are two of these schemes:
• Basic authentication
• In basic authentication, the client sends the user name and password in the
request header. It encodes them with base64, which is an encoding technique
that converts the pair into a set of 64 characters for safe transmission.

13-03-2025 75
• Bearer authentication
• The term bearer authentication refers to the process of giving access control to the token
bearer. The bearer token is typically an encrypted string of characters that the server
generates in response to a login request. The client sends the token in the request headers to
access resources.
• API keys
• API keys are another option for REST API authentication. In this approach, the server assigns
a unique generated value to a first-time client. Whenever the client tries to access resources,
it uses the unique API key to verify itself. API keys are less secure because the client has to
transmit the key, which makes it vulnerable to network theft.
• OAuth
• OAuth combines passwords and tokens for highly secure login access to any system. The
server first requests a password and then asks for an additional token to complete the
authorization process. It can check the token at any time and also over time with a specific
scope and longevity.

13-03-2025 76
What does the RESTful API server response
contain?
• REST principles require the server response to contain the following main
components:
• Status line
• The status line contains a three-digit status code that communicates request
success or failure. For instance, 2XX codes indicate success, but 4XX and 5XX
codes indicate errors. 3XX codes indicate URL redirection.
• The following are some common status codes:
• 200: Generic success response
• 201: POST method success response
• 400: Incorrect request that the server cannot process
• 404: Resource not found

13-03-2025 77
• Message body
• The response body contains the resource representation. The server selects
an appropriate representation format based on what the request headers
contain. Clients can request information in XML or JSON formats, which
define how the data is written in plain text. For example, if the client requests
the name and age of a person named John, the server returns a JSON
representation as follows:
• '{"name":"John", "age":30}'
• Headers
• The response also contains headers or metadata about the response. They
give more context about the response and include information such as the
server, encoding, date, and content type.

13-03-2025 78
How can AWS help you with RESTful API
management?
• Amazon API Gateway is a fully managed service that makes it easy for developers
to create, publish, maintain, monitor, and secure APIs at any scale. Using API
Gateway, you can create RESTful APIs for real-time two-way communication
applications:
• Using API Gateway, you can:
• Provide users with high-speed performance for both API requests and
responses.
• Authorize access to your APIs with AWS Identity and Access Management
(IAM) and Amazon. Cognito, both of which provide native OAuth support.
• Run multiple versions of the same API simultaneously with API Gateway to
quickly iterate, test, and release new versions.
• Monitor performance metrics and information about API calls, data latency,
and error rates from the API Gateway.
13-03-2025 79
How do RESTful APIs work?
• The basic function of a RESTful API is the same as browsing the internet. The
client contacts the server by using the API when it requires a resource. API
developers explain how the client should use the REST API in the server
application API documentation. These are the general steps for any REST API call:
[Link] client sends a request to the server. The client follows the API documentation
to format the request in a way that the server understands.
[Link] server authenticates the client and confirms that the client has the right to
make that request.
[Link] server receives the request and processes it internally.
[Link] server returns a response to the client. The response contains information
that tells the client whether the request was successful. The response also
includes any information that the client requested.
• The REST API request and response details vary slightly depending on how the
API developers design the API.
13-03-2025 80
AJAX Introduction

• AJAX = Asynchronous JavaScript And XML.


• AJAX is not a programming language.
• AJAX is a misleading name. AJAX applications might use XML to transport data,
but it is equally common to transport data as plain text or JSON text.
• AJAX allows web pages to be updated asynchronously by exchanging data with a
web server behind the scenes. This means that it is possible to update parts of a
web page, without reloading the whole page.
• AJAX just uses a combination of:
• A browser built-in XMLHttpRequest object (to request data from a web
server)
• JavaScript and HTML DOM (to display or use the data)
13-03-2025 81
AJAX
• With Ajax, we 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.

13-03-2025 82
AJAX Example Explained
• HTML Page
• <!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
</body>
</html>
• The HTML page contains a <div> section and a <button>.
• The <div> section is used to display information from a server.
• The <button> calls a function (if it is clicked).
• The function requests data from a web server and displays it:

13-03-2025 83
AJAX Example Explained
• Function loadDoc()
• function loadDoc() {
var xhttp = new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("demo").innerHTML = [Link];
}
};
[Link]("GET", "ajax_info.txt", true);
[Link]();
}

13-03-2025 84
AJAX Example Explained
• The "ajax_info.txt" file used in the example above, is a simple text file and looks
like this:
• <h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

13-03-2025 85
How AJAX Works

13-03-2025 86
How AJAX Works

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

13-03-2025 87
AJAX - The XMLHttpRequest Object
• The keystone of AJAX is the XMLHttpRequest object.
• The XMLHttpRequest Object
• All modern browsers support the XMLHttpRequest object.
• The XMLHttpRequest object can be used to exchange data with a server
behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
• Create an XMLHttpRequest Object
• All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera) have a
built-in XMLHttpRequest object.
• Syntax for creating an XMLHttpRequest object:
• variable = new XMLHttpRequest();

13-03-2025 88
13-03-2025 89
XMLHttpRequest Object Methods
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request


getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
90
13-03-2025
XMLHttpRequest Object Properties
Property Description
onreadystatechange Defines a function to be called when the readyState property changes

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")

13-03-2025 91
AJAX - Send a Request To a Server
• The XMLHttpRequest object is used to exchange data with a server.
• Send a Request To a Server
• To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
• [Link]("GET", "ajax_info.txt", true);
[Link]();

Method Description
open(method, url, Specifies the type of request
async)
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)

13-03-2025 92
GET or POST?

• GET is simpler and faster than POST, and can be used in most cases.
• However, always use POST requests when:
• A cached file is not an option (update a file or database on the server).
• Sending a large amount of data to the server (POST has no size limitations).
• Sending user input (which can contain unknown characters), POST is more robust
and secure than GET.

13-03-2025 93
GET Requests
• A simple GET request:

13-03-2025 94
• In the example shown, you may get a cached result. To avoid this, add a unique ID
to the URL:

13-03-2025 95
• If you want to send information with the GET method, add the
information to the URL:

13-03-2025 96
POST Requests
• A simple POST request:

13-03-2025 97
• To POST data like an HTML form, add an HTTP header with setRequestHeader().
Specify the data you want to send in the send() method:

13-03-2025 98
Method Description
setRequestHeader(header, Adds HTTP headers to the request
value)
header: specifies the header name
value: specifies the header value

13-03-2025 99
The url - A File On a Server

• The url parameter of the open() method, is an address to a file on a


server:
• [Link]("GET", "ajax_test.asp", true);
• The file can be any kind of file, like .txt and .xml, or server scripting
files like .asp and .php (which can perform actions on the server
before sending the response back).

13-03-2025 100
Asynchronous - True or False?

• Server requests should be sent asynchronously.


• The async parameter of the open() method should be set to true:
• [Link]("GET", "ajax_test.asp", true);
• By sending asynchronously, the JavaScript does not have to wait for the server
response, but can instead:
• execute other scripts while waiting for server response
• deal with the response after the response is ready

13-03-2025 101
The onreadystatechange Property
• With the XMLHttpRequest object you can define a function to be executed when
the request receives an answer.
• The function is defined in the onreadystatechange property of the
XMLHttpResponse object:

13-03-2025 102
• The "ajax_info.txt" file used in the example above, is a simple text file and looks
like this:
• <h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

13-03-2025 103
Synchronous Request

• To execute a synchronous request, change the third parameter in the open()


method to false:
• [Link]("GET", "ajax_info.txt", false);
• Sometimes async = false are used for quick testing. You will also find synchronous
requests in older JavaScript code.
• Since the code will wait for server completion, there is no need for an
onreadystatechange function:

13-03-2025 104
13-03-2025 105
• Synchronous XMLHttpRequest (async = false) is not recommended because the
JavaScript will stop executing until the server response is ready. If the server is
busy or slow, the application will hang or stop.
• Synchronous XMLHttpRequest is in the process of being removed from the web
standard, but this process can take many years.
• Modern developer tools are encouraged to warn about using synchronous
requests and may throw an InvalidAccessError exception when it occurs.

13-03-2025 106
AJAX - Server Response

• The onreadystatechange Property


• The readyState property holds the status of the XMLHttpRequest.
• The onreadystatechange property defines a function to be
executed when the readyState changes.
• The status property and the statusText property holds the status
of the XMLHttpRequest object.

13-03-2025 107
Property Description
onreadystatech Defines a function to be called when the readyState property changes
ange

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status 200: "OK"


403: "Forbidden"
404: "Page not found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

• The onreadystatechange function is called every time the readyState changes.


• When readyState is 4 and status is 200, the response is ready:
13-03-2025 108
• The onreadystatechange event is triggered four times (1-4), one time for each
13-03-2025 change in the readyState. 109
Using a Callback Function

• A callback function is a function passed as a parameter to another function.


• If you have more than one AJAX task in a website, you should create one function
for executing the XMLHttpRequest object, and one callback function for each
AJAX task.
• The function call should contain the URL and what function to call when the
response is ready.

13-03-2025 110
13-03-2025 111
• Server Response Properties
Property Description
responseText get the response data as a string
responseXML get the response data as XML data

• Server Response Methods


Method Description
getResponse Returns specific header information from the server resource
Header()
getAllRespons Returns all the header information from the server resource
eHeaders()

13-03-2025 112
The responseText Property
• The responseText property returns the server response as a JavaScript string, and
you can use it accordingly:

13-03-2025 113
The responseXML Property

• The XML HttpRequest object has an in-built XML parser.


• The responseXML property returns the server response as an XML
DOM object.
• Using this property you can parse the response as an XML DOM
object:

13-03-2025 114
13-03-2025 115
The getAllResponseHeaders() Method
• The getAllResponseHeaders() method returns all header information from the
server response.

13-03-2025 116
The getResponseHeader() Method
• The getResponseHeader() method returns specific header information from the
server response.

13-03-2025 117
AJAX XML Example
• AJAX can be used for interactive communication with an XML file.

13-03-2025 118
AJAX XML Example

13-03-2025 119
Example Explained

• When a user clicks on the "Get CD info" button above, the loadDoc() function is
executed.
• The loadDoc() function creates an XMLHttpRequest object, adds the function to
be executed when the server response is ready, and sends the request off to the
server.
• When the server response is ready, an HTML table is built, nodes (elements) are
extracted from the XML file, and it finally updates the element "demo" with the
HTML table filled with XML data:

13-03-2025 120
• The XML file used in the example above looks like this: "cd_catalog.xml".
13-03-2025 121
AJAX PHP Example

• AJAX is used to create more interactive applications.


• AJAX PHP Example
• The following example demonstrates how a web page can
communicate with a web server while a user types characters in
an input field:
• Example
Start typing a name in the input field below:
First name: Suggestions:

13-03-2025 122
Example

• In the example above, when a user types a character in the input field, a function
called "showHint()" is executed.
• The function is triggered by the onkeyup event.
• Here is the HTML code:

13-03-2025 123
13-03-2025 124
• Code explanation:
• First, check if the input field is empty ([Link] == 0). If it is, clear the content
of the txtHint placeholder and exit the function.
• However, if the input field is not empty, do the following:
• Create an XMLHttpRequest object
• Create the function to be executed when the server response is ready
• Send the request off to a PHP file ([Link]) on the server
• Notice that q parameter is added [Link]?q="+str
• The str variable holds the content of the input field

13-03-2025 125
The PHP File - "[Link]"
• The PHP file checks an array of names, and returns the corresponding name(s) to
the browser:

13-03-2025 126
JSON in AJAX
• AJAX is a very popular concept that is used to update the page without reloading
the page.
• AJAX stands for Asynchronous Javascript And XML and because of that many
Developers think that AJAX will only use XML to export and import data but that
is not true.
• AJAX can use XML to transport any kind of data but can also transport data in
JSON or any other plain text.

13-03-2025 127
JSON in AJAX
• JavaScript Object Notation (JSON) is a format in which we store data and can use
that data in transferring from one computer to another computer.
• It is very easy to understand and very light in weight.
• JSON is any simple text and can be converted to JavaScript Objects and strings.
• It is language-independent, as many programming language support reading and
generating JSON text.

13-03-2025 128
• Advantages of using JSON instead of XML in AJAX:
• The Code of JSON will be short in comparison to XML that’s why transferring
data will be smooth
• JSON is easier to understand in comparison with XML
• In JSON we can easily represent a NULL Value.
• AJAX works on Request and Response means AJAX will Request anything from the
server and the server will give the Response back to AJAX.
• Built-in Object of JavaScript known as “XMLHttpRequest” is used to send
Responses and get Requests.
• There are some of the properties and methods of XMLHttpRequest, are described
below:

13-03-2025 129
• new XMLHttpRequest: It will create a new object by which we can send requests
and receive responses.
• open(): It will specify any request. It takes various parameters like types of
requests(GET or POST), location of server file, etc.
• send(): It is used to send a request to the server. It contains a string as a
parameter if it is used for POST requests.
• onload: It is the property of XMLHttpRequest object which is used to define a
function that will be called on complete loading of data.
• onreadystatechange: It is the property of XMLHttpRequest which is used to
define a function that will be called on change of ready state. readystate is also a
property of the XMLHttpRequest object.

13-03-2025 130
• readystate: It is used to represent the status of the request. It can contain 5
values and every value has a different meaning.
• 0 means the request is not initialized
• 1 means Connection with the server is established
• 2 means the request is received
• 3 means processing the request
• 4 means the request is finished
• status: It is the property of XMLHttpRequest which is used to represent the status
number of any request
• responseText: It is the property of XMLHttpRequest which is used to return the
data of the response as a string

13-03-2025 131
Steps for Sending the request with AJAX:

• Create a new XMLHttpRequest.


• Use the open() method of XMLHttpRequest to specify the request
• Use send() method of XMLHttpRequest to send request to the server

13-03-2025 132
Steps for Getting a response from the
server:
• Use the “onload” or “onreadystatechange” property of XMLHttpRequest to define
a function that will help us to use our response at any place.
• You can use responseText inside that function to show your data anywhere on the
webpage because responseText contains response data as a string.
• If you used “onload” property then you can use the responseText property
directly inside the function. But if you will use “onreadystatechange” then you
have to use the if condition to verify whether readystate became 4 or not
because onreadystatechange will call the function every time when readystate
changes but we need to use our responseText to show data when readystate
becomes 4 because the response will be fully loaded only when the readystate
becomes 4.

13-03-2025 133
• Example 1: In this example, we will see how we can GET data from a server file
using AJAX. Here, we took the server file in JSON format.

13-03-2025 134
13-03-2025 135
13-03-2025 136
• Javascript object will be converted into JSON format and then that data will be
transported to the server side. On the server side that JSON data will be
converted into Server side language.
• JSON object has 2 methods, i.e., stringify() and parse() method which is used to
convert the Javascript object into JSON string and back into a Javascript object.
• [Link](): It will convert the Javascript object into the JSON format string.
• [Link](): It will convert the JSON string back into a javascript object

13-03-2025 137
Example 2: In this example, we are using [Link]() to convert the javascript
objects into JSON format.

13-03-2025 138
Example 3: In this example, we are using [Link]() to convert the JSON data
that we obtained in the above example, into a javascript object.

13-03-2025 139
How to do exception handling in Ajax ?

• The Ajax component exploits this ability of JavaScript to send asynchronous HTTP
requests, receive the XML response (as well as other formats), and update part of
a website (using JavaScript) without reloading or refreshing the entire site.
• The three methods that we need to know to make AJAX requests are as follows.
• This method is called when an HTTP request is successful.
• $.ajax(options).done(callback)
• This method is called when an HTTP request fails.
• $.ajax(options).fail(callback)
• This method is called always, be the HTTP request fails or is successful.
• $.ajax(options).always(callback)

13-03-2025 140
• Example: We are going to see how to use AJAX fail() methods to handle the error
in the HTTP requests. The fail() callback takes 3 parameters where the first
parameter is a JSON error object, the second parameter is given a reason in text
format and the last parameter is for the error thrown by the HTTP request. The
whole object with values of the different parameters is shown in the text area.
The output is shown in JSON format to show you the value and type of the value
that is received as a parameter when an HTTP request fails.
• The format of the output is as follows.

13-03-2025 141
Example: In this example, we will see how to handle exceptional handling AJAX.

13-03-2025 142
13-03-2025 143
13-03-2025 144

You might also like