0% found this document useful (0 votes)
13 views12 pages

LM Unit4

Unit-4 covers AJAX technology, detailing its fundamentals, the differences between synchronous and asynchronous web applications, and the workings of XMLHttpRequest. AJAX enables dynamic data exchange with the server without reloading the page, enhancing web application speed and responsiveness. The document also discusses the advantages and disadvantages of AJAX, its architecture, and provides examples of its implementation using JavaScript and jQuery.

Uploaded by

patelhani5544
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)
13 views12 pages

LM Unit4

Unit-4 covers AJAX technology, detailing its fundamentals, the differences between synchronous and asynchronous web applications, and the workings of XMLHttpRequest. AJAX enables dynamic data exchange with the server without reloading the page, enhancing web application speed and responsiveness. The document also discusses the advantages and disadvantages of AJAX, its architecture, and provides examples of its implementation using JavaScript and jQuery.

Uploaded by

patelhani5544
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/ 12

Unit-4: AJAX (Asynchronous JavaScript and XML)

Unit-4: AJAX (Asynchronous JavaScript and XML):


4.1 Fundamentals of AJAX technology:
4.1.1 Difference between Synchronous and Asynchronous web application
4.1.2 XMLHttpRequest technology
4.2 XMLHttpRequest
4.2.1 Properties :( onReadyStateChange, readyState, responseText,
responseXML)
4.2.2 XMLHttpRequest Methods : (Open(), send(), setRequestHeader())
4.3 Working of AJAX and its architecture

Fundamentals of AJAX technology:


▪ Ajax is a technology that allows us to dynamically send and receive data from the
server without having to reload the page or browser.
▪ Ajax works very well with XML and JSON, in fact ‘X’ in AJAX stands for XML.
▪ In web development Asynchronous means getting information without reloading
the page.
▪ AJAX is not a programming language but an approach to use existing standards.
▪ AJAX just uses a combination of:
o A browser built-in XMLHttpRequest object (to request data from a web
server)
o JavaScript and HTML DOM (to display or use the data)

Where it is used?
There are too many web applications running on the web that are using AJAX
Technology. Some are : 1. Gmail 2. Face book 3. Twitter 4. Google maps 5. YouTube
etc.,

Web application model:


web application model classify in Synchronous(classic web application model ) and
Asynchronous(AJAX Web application model).
• Synchronous (Classic Web-Application Model) A synchronous request blocks the
client until operation completes i.e. browser is not unresponsive. In such case,
JavaScript Engine of the browser is blocked.

[By Dr.Ami Desai ] pg. 1


As you can see in the above image, full page is refreshed at request time and user is
blocked until request completes.

Asynchronous (AJAX Web-Application Model):


An asynchronous request doesn’t block the client i.e. browser is responsive. At that
time, user can perform other operations also. In such case, JavaScript Engine of the
browser is not blocked

[By Dr.Ami Desai ] pg. 2


As you can see in the above image, full page is not refreshed at request time and user
gets response from the AJAX Engine. to understand asynchronous communication by
the given image.

Difference between Synchronous and Asynchronous web application.(Synchronous


Vs Asynchronous)
Synchronous Asynchronous
The synchronous request blocks the An asynchronous request doesn’t block the
client (browser) until operation client i.e. browser is responsive. At that
completes i.e. browser is time, user can perform some operations
unresponsive. In such case, javascript also. In such case, javascript engine of the
engine of the browser is blocked. browser is not blocked.
When we don’t want processing When we want processing multiple
multiple operations at the same time, operations simultaneously, we use
we use Synchronous web Apps. Asynchronous web Apps.
Here, the tasks are dependent on each Here, the tasks are independent of each
other. other.
Example: Example:
• Chat Rooms • Email
• Telephonic Conversations • Forums
• Video Conferencing • Letters

[By Dr.Ami Desai ] pg. 3


In Synchronous web transmission,
In Asynchronous web transmission, there
there is no gap present between
is a gap present between data.
data.
Web page loading slow because it Web page loading fast because it reload
reload whole page selected part/portion of web page.

Working of AJAX
Traditional web applications are created by adding loosely web pages through links in
a predefined order. Where the user can move from one page to another page to
interact with the different portions of the applications.

Also, HTTP requests are used to submit the web server in response to the user action.
On receiving the request, the web server fulfills the request by returning a new
webpage which, then displays on the web browser. This process includes lots of pages
refreshing and waiting.

AJAX change this whole working model by sharing the minimum amount of data
between the web browser and server asynchronously. It speedup up the working
of the web applications.
It creates an additional layer known as AJAX engine in between the web application
and webserver due to which we can make background server calls using JavaScript
and retrieve the required data, can update the requested portion of a web page
without casing full reload of the page.
Asynchronous processes reduce the workload of the web server by dividing the work
with the client computer. Due to the reduced workload web servers become more
responsive and fast.

Advantages and Disadvantages of AJAX


Advantages of AJAX

[By Dr.Ami Desai ] pg. 4


• Speed
Reduce the server traffic in both side request. Also reducing the time
consuming on both side response. Speed up request and response.
• Interaction
AJAX is much responsive, whole page (small amount of) data transfer at a time.
• XMLHttpRequest
XMLHttpRequest has an important role in the Ajax web development
technique. XMLHttpRequest is special JavaScript object that was designed by
Microsoft. XMLHttpRequest object call as a asynchronous HTTP request to the
Server for transferring data both side. It's used for making requests to the non-
Ajax pages.
• Asynchronous calls
AJAX make asynchronous calls to a web server. This means client browsers are
avoid waiting for all data arrive before start the rendering.
• Form Validation
This is the biggest advantage. Form are common element in web page.
Validation should be instant and properly, AJAX gives you all of that, and
more.
• Bandwidth Usage
No require to completely reload page again. AJAX is improve the speed and
performance. Fetching data from database and storing data into database
perform background without reloading whole page.
Disadvantages of AJAX
• View source is allowed and anyone can view the code source written for AJAX.
• ActiveX requests are enabled only in Internet Explorer and newer latest
browser.

Working of AJAX and its architecture


AJAX communicates with the server using XMLHttpRequest object. Let's try to
understand the flow of ajax or how ajax works by the image displayed below.

[By Dr.Ami Desai ] pg. 5


As you can see in the above example, XMLHttpRequest object plays a important role.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest
object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
AJAX Components
AJAX is not a technology but group of inter-related technologies.
AJAX Technologies includes:
• HTML/XHTML and CSS: HTML/XHTML and CSS These technologies are used for
displaying content and style. It is mainly used for presentation.
• DOM (jquery): DOM It is used for dynamic display and interaction with data.
• XML or JSON(JavaScript Object Notation) : XML or JSON(Javascript Object
Notation) For carrying data to and from server. JSON is like XML but short and
faster than XML.
• XMLHttpRequest Object : XMLHttpRequest Object For asynchronous
communication between client and server.
• JavaScript: JavaScript It is used to bring above technologies together.
Independently, it is used mainly for client side validation.

[By Dr.Ami Desai ] pg. 6


AJAX - XMLHttpRequest
In AJAX, XMLHttpRequest is used to exchange data to or from the web server in the
background while the user/client working in the foreground and then update the part
of the web page with the received data without reloading the whole page.
We can also say that XMLHttpRequest (XHR) can be used by various web browser
scripting languages like JavaScript, JScript, VBScript, etc., to exchange XML data to or
from the web server with the help of HTTP.

Apart from XML, XMLHttpRequest can also fetch data in various formats like JSON, etc.
It creates an asynchronous connection between the client side and the server side.

Syntax
variableName = new XMLHttpRequest()

Where using a new keyword along with XMLHttpRequest() constructor we can be able
to create a new XMLHttpRequest object. This object must be created before calling
the open() function to initialise it before calling send() function to send the request
to the web server.
▪ To do the request, we need 3 steps:
1. Create XMLHttpRequest:
let xhr = new XMLHttpRequest();
o The constructor has no arguments.
2. Initialize it, usually right after new XMLHttpRequest: it is open() for
configure the request only.
xhr.open(method, URL, [async, user, password])
o This method specifies the main parameters of the request:
✓ method – HTTP-method. Usually "GET" or "POST".
✓ URL – the URL to request, a string, can be URL object.
✓ async – if explicitly set to false, then the request is
synchronous, we’ll cover that a bit later.
✓ user, password – login and password for basic HTTP auth (if
required).
3. Send it out. :to start activity call send()
xhr.send([body])
o This method opens the connection and sends the request to server.
The optional body parameter contains the request body.
o Some request methods like GET do not have a body. And some of
them like POST use body to send the data to the server.

XMLHttpRequest Object Methods

Sr.No. Method Name & Descrip on

[By Dr.Ami Desai ] pg. 7


1 new XMLHttpRequest(): It is used to create an XMLHttpRequest() object
2 getAllResponseHeaders():It is used to get the all header information(content type,
authentication details, caching directives, and much more.). provides all headers as a
single string. Headers are formatted as header-name: value separated by newlines (\n).
xhr.getAllResponseHeaders()
3 getResponseHeader(): It is used to get the specific header information
Ex. xhr.getResponseHeader(‘content-type’)
Here, it provide type of response from server (it may by json,xml…etc)
4 open(method, url, async, user, psw): It is used to initialise the request parameters
and configure the connection/file.
Here,
method: request type GET or POST or Other types
url: file location
async: for the asynchronous set to true or for synchronous set to false
user: for optional user name
psw: for optional password
5 send():It is used to send requests to the web server. It is generally used for GET
requests.
6 send(string):It is used to send requests to the server. It is generally used for POST
requests.
7 setRequestHeader(): It is used to add key/value pair to the header.
• sets the value of an HTTP request header.
• When using setRequestHeader(), we must call it after calling open(), but
before calling send().
Syntax: obj.setRequestHeader(header, value);
• Header: The name of the header whose value is to be set.
• Value: The value to set as the body of the header.
Ex:
xmlHttp.setRequestHeader("Content-Type", "application/json");
here, Content-Type: Specifies the type of data being sent (JSON in this
case).

XMLHttpRequest Object Properties


Sr.No. Property Name & Description
1 onreadystatechange:Set the callback function which handles request state
changes.
2 readyState:It is used to hold the status of XMLHttpRequest. It has the following
values−
0. It represents the request is not initalise
1. It represents the server connection established
2.It represents the request received

[By Dr.Ami Desai ] pg. 8


3.It represents the request is in processing
4.It represents the request finished and the response is ready
3 responseText:It is used to return the response data as a string
4 responseXML: It is used to return the response data as XML data
5 Status:It is used to return the status number of a request.
For example
200: for OK
403: for Forbidden
404: for Not Found
6 StatusText:It is used to return the status text. For example, OK, Not Found, etc.

Examples:
onload
▪ With the XMLHttpRequest object we can define a callback function to be
executed when the request receives an answer.
▪ The function is defined in the onload property of
the XMLHttpRequest object:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
</script>
</body>
</html>

Onreadystatechange:
▪ The readyState property holds the status of the XMLHttpRequest.
▪ The onreadystatechange property defines a callback function to be
executed when the readyState changes.
Data.txt

[By Dr.Ami Desai ] pg. 9


<TABLE BORDER="1">
<tr><td>Name </td><td> Contact No</td> </tr>
<tr><td>Ram </td><td> 999952255</td> </tr>
<tr><td>Nila </td><td> 888545221</td> </tr>
<tr><td>Raj </td><td> 784555622</td> </tr>
</TABLE>
Index.html
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest(); //generate object of request
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "data.txt", true);//configure the request
xhttp.send();//start the activity
}
</script>
</body>
</html>
getJSON()
▪ It is a jquery Method to get the JSON data using request.
$.getJSON(url,[data, success])
$.getJSON(“xyz.json”,function(){});
Data.json
[
{ "name": "Raj" },
{ "name": "Bina" },
{ "name": "Lina" }
]

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="d1"></div>

[By Dr.Ami Desai ] pg. 10


<button id="btn">Click</button>

<script>
$(document).ready(function () {
$("#btn").click(function () { // Use # for ID selectors
$.getJSON("data1.json", function (data) {
$("#d1").empty(); // Clear previous content
for (let i = 0; i < data.length; i++) {
$("#d1").append("<p>" + data[i].name + "</p>"); // Append names in <p> tags
}
}).fail(function () {
$("#d1").text("Error: Unable to load data.");
});
});
});
</script>
</body>
</html>

jquery.ajax() or $.ajax()
▪ The ajax() method in jQuery is used to perform an AJAX request or
asynchronous HTTP request.

Data.txt
<TABLE BORDER="1">
<tr><td>Name </td><td> Contact No</td> </tr>
<tr><td>Ram </td><td> 999952255</td> </tr>
<tr><td>Nila </td><td> 888545221</td> </tr>
<tr><td>Raj </td><td> 784555622</td> </tr>
</TABLE>
Index.html
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<h1>text -> jQuery</h1>
<button id="textbtn">Load Text File</button>
<div id="content" style="margin-top: 20px; border: 1px solid #ccc;
padding: 10px;"></div>

<script>
$(document).ready(function () {
$("#textbtn").click(function () {
$.ajax({
url: "data.txt", // Path to your text file
type: "GET",

[By Dr.Ami Desai ] pg. 11


success: function (data) {
// Display the text file content in the div
//$("#content").text(data);
// Display the html file content in div
$("#content").html(data);
},
error: function () {
// Display an error message if the file can't be loaded
$("#content").text("Error: Unable to load the text file.");
}
});
});
});
</script>
</body>
</html>

[By Dr.Ami Desai ] pg. 12

You might also like