You are on page 1of 12

AJAX- not an library but a technique to create interactive web sites

Ajax, which stands for Asynchronous JavaScript and XML, is a set of techniques for creating
highly interactive web sites and web applications. The idea is to make what’s on the Web appear
to be local by giving you a rich user experience, offering you features that usually only appear in
desktop applications.
The emphasis in Ajax applications is to update the web page, using data fetched from the
Internet, without refreshing the web page in the browser. You saw an example of that with
Google Suggest, where a drop-down list appears in the browser without a page refresh.
The term “Ajax” was created by Jesse James Garrett, president of Adaptive Path, in a February
18, 2005 article collecting the technologies that already existed, and which make up Ajax, under
one umbrella term.

AJAX LOADS IN DATA WITHOUT REFRESHING THE BROWSER.

We aren’t getting enough orders on our Web site,” storms the CEO.
“People just don’t like clicking all those buttons and waiting for a new page all the time. It’s too
distracting.”
“How about a simpler solution?” you ask. “What if people could stay on the same page and just
drag the items they want to buy to a shopping cart? No page refreshes, no fuss, no muss.”
“You mean people wouldn’t have to navigate from page to page to add items to a shopping cart
and then check out? Customers could do everything on a single Web page?”
“Yep,” you say. “And that page would automatically let our software on the server know what
items the customer had purchased — all without having to reload the Web page.”
“I love it!” the CEO says. “What’s it called?”
“Ajax,” you say.
Welcome to the world of Ajax, the technology that lets Web software act like desktop software.
One of the biggest problems with traditional Web applications is that they have that “Web” feel
— you have to keep clicking buttons to move from page to page, and watch the screen flicker as
your browser loads
a new Web page. Ajax is here to take care of that issue, because it enables you grab data from
the server without reloading new pages into the browser.
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 stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating
better, faster, and more interactive web applications with the help of XML, HTML, CSS, and
Java Script.
 Ajax uses XHTML for content, CSS for presentation, along with Document Object
Model and JavaScript for dynamic content display.
 Conventional web applications transmit information to and from the sever using
synchronous requests. It means you fill out a form, hit submit, and get directed to a new
page with new information from the server.
 With AJAX, when you hit submit, JavaScript will make a request to the server, interpret
the results, and update the current screen. In the purest sense, the user would never know
that anything was even transmitted to the server.
 XML is commonly used as the format for receiving server data, although any format,
including plain text, can be used. XML was designed to store and transport
data.AJAX is a web browser technology independent of web server software.
 A user can continue to use the application while the client program requests information
from the server in the background.
 Intuitive and natural user interaction. Clicking is not required, mouse movement is a
sufficient event trigger.
 Data-driven as opposed to page-driven
AJAX cannot work independently. It is used in combination with other technologies to create
interactive webpages.
JavaScript

 Loosely typed scripting language.


 JavaScript function is called when an event occurs in a page.
 Glue for the whole AJAX operation.
DOM

 API for accessing and manipulating structured documents.


 Represents the structure of XML and HTML documents.
CSS

 Allows for a clear separation of the presentation style from the content and may be
changed programmatically by JavaScript
XMLHttpRequest

 JavaScript object that performs asynchronous interaction with the server.


 Difference between XML and HTML
 HTML is used for designing a web-page to be rendered on the client side
 XML is used basically to transport data between the application and the database.

 XML was designed to carry data - with focus on what data is
 HTML was designed to display data - with focus on how data looks
 XML tags are not predefined like HTML tags are

XML is self descriptive means

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

EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
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, IE7+, Edge, Safari Opera) have a built-in
XMLHttpRequest object.

variable = new XMLHttpRequest();

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

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"

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

Synchronous requests
var ajax = new XMLHttpRequest();
ajax.open("GET", url, false);
ajax.send(null);

Why synchronous requests are bad?


 your code waits for the request to completely finish before proceeding
 easier for you to program, but ...
 the user's entire browser locks up until the download is completed
 a terrible user experience (especially if the file is very large)

Asynchronous requests, basic idea


var ajax = new XMLHttpRequest();
ajax.onreadystatechange = functionName;
ajax.open("get", url, true);
ajax.send(null);
// don't process ajax.responseText here, but in your function
 attach an event handler to the request's onreadystatechange event
 pass true as third parameter to open
 handler will be called when request state changes, e.g. finishes
 function's code will be run when request is complete

Set up local web server on Windows


Unlike Linux and Mac OS X, Windows is not Unix-based, so there is no one-liner to install it.
Fortunately there are several install wizards that bundle things like Apache, MySQL, and PHP
together to make our lives easier. One of them is XAMPP.

Note: XAMPP is available for Linux and Mac OS X too.

Download the Windows version of XAMPP and begin installation. Execute the installer when
prompted. You can select only Apache if all you need is a web server. However if you are
planning on using a database, you may want to select MySQL as well.
Continue through the installation and click “Finish” when complete. By default, the XAMPP
control panel will be launched.

Click “Start” for Apache and MySQL if needed.

If you navigate to “127.0.0.1” or “localhost” in your web browser, you should see the XAMPP
configuration page.

To create a new webpage, the procedure is the same. Open up notepad and create a sample
HTML file. Name it “hello.html.”
Save it in the document root located in c:\xampp\htdocs\.

Now navigate to it using your web browser by going to “127.0.0.1/hello.html.”

Example Program
Two files: 1. Java4s.txt
2. hello.html
Save both files on e:/xampp/htdocs

Java4s.txt content : welcome to nitte


Hello.html content
<html>
<head>
<script type="text/javascript">
function fun1()
{ 1. Create request object
var a= new XMLHttpRequest();

a.onreadystatechange=function()
3. Activated only when the
{
response is received and the
if (a.readyState==4 && a.status==200)
ready state changes. Displays
{
the result.
document.getElementById("myDiv").innerHTML=a.responseText;
}
}

a.open("POST","java4s.txt",true); 2. On creating the control directly


a.send(); jumps here to open the request and
} // fun1() close send request to server.
</script>

</head>
<body>

<div id="myDiv" style="width: 300px; height: 30px;">Click on the button below</div>


<button type="button" onclick="fun1()">Change Content</button>

</body>
</html>

 Once the document loaded then immediately we will be able to see one button Change
Content , and see i have been given onclick=”fun1()” [ line number 33 ] means once we click
on this button controller will go to line number 4 and will starts execute that fun1()
 At line number 6, i have taken one variable with name a
 For any ajax program, we must create one request object to send our ajax request to the
server, that ajax object is nothing but XMLHttpRequest object
 See line number 8, i have written window.XMLHttpRequest means am checking whether my
browser supports XMLHttpRequest object or not, if yes assigning XMLHttpRequest object
into a [ a=new XMLHttpRequest(); ] else i mean if our web browser doesnt
supports XMLHttpRequest object then we can assign ActiveXObject [ which supports old
web browsers ] into our variable a [ a=new ActiveXObject(“Microsoft.XMLHTTP”); ]
 So from line numbers 8 -15 request object creation work been done
 Now controller directly jumps to line number 25, and opens the connection and send the
request to java4s.txt (this is my notepad file), see actually the 3rd parameter i have given
as true means Asynchronous data transfer will be activated
 Finally request will be sent in line number 26, that’s it.
 If server sends the response back to our application then controller will automatically execute
from line number 17 – 23, you may get one doubt like why its not executed initially… ? there
is a reason actually this a.onreadystatechange=function() executes only when we get the
response from the server, hope you are clear 😉

 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.

<!DOCTYPE html>
<html>
<body>

<div id="demo">

<h1>The XMLHttpRequest Object</h1>

<button type="button"
onclick="loadDoc('ajax_info.txt', myFunction)">Change Content
</button>
</div>

<script>

function loadDoc(url, cFunction) {


var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}

function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseText;
}

</script>
</body>
</html>

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
getResponseHeader() Returns specific header information from the server resource
getAllResponseHeaders() Returns all the header information from the server resource

The responseText Property


The responseText property returns the server response as a JavaScript string, and you can use it
accordingly:

Example
document.getElementById("demo").innerHTML = xhttp.responseText;
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.

You might also like