Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Asynchronous Javascript And Xml

 Introduction to AJAX
◦ What is AJAX?
◦ Why AJAX is necessary?
◦ How AJAX works
 XMLHttp Request
 XMLHttp Response
 Events
 Database in AJAX
 AJAX is Asynchronous Javascript And Xml
 New way to use existing standards
 Exchanging data with a server and updating parts of a web
page – without reloading the whole page.
 Communication between Server and Client through
asynchronous requests.
 XML or JSON are commonly used format for receiving server
data.
 AJAX is a technique for producing faster, more interactive and
usable web pages without page refreshment.

 AJAX was developed by five main components: HTML,


JAVA SCRIPT, CSS, XML and XMLHTTP REQUEST.

 AJAX is not a technology it is a combination of technologies.

 XMLHTTP Request: This object allows asynchronous


exchange of data between the server and client.

 It is an API that uses javascript to transfer the data like xml


using HTTP protocol.
Before understanding AJAX, let’s understand classic web
application model and ajax web application model first.

Synchronous (Classic Web-Application Model)

A synchronous request blocks the client until operation completes


i.e. browser is unresponsive. In such case, javascript engine of the
browser is blocked.
As you can see in the above image, full page is refreshed at
request time and user is blocked until request completes.
Let's understand it another way.
An asynchronous request doesn’t block the client i.e.
browser is responsive. At that time, user can perform
another operations also. In such case, javascript engine of
the browser is not blocked.
As you can see in the above image, full page is not refreshed at
request time and user gets response from the ajax engine.
Let's try to understand asynchronous communication by the image
given below.
Here is a list of some famous web applications that make use of AJAX.
 Google Maps

A user can drag an entire map by using the mouse, rather than clicking on
a button. http://maps.google.com/
 Google Suggest

As you type, Google will offer suggestions. Use the arrow keys to
navigate the results.
http://www.google.com/webhp?complete=1&hl=en
 Gmail

Gmail is a webmail, built on the idea that email can be more intuitive,
efficient and useful. http://gmail.com/
 Yahoo Maps (new)

Now it's even easier and more fun to get where you're going!
http://maps.yahoo.com/
AJAX is based on the following open standards −
◦ Browser-based presentation using HTML and Cascading
Style Sheets (CSS).
◦ Data is stored in XML format and fetched from the server.
◦ Behind-the-scenes data fetches using XMLHttpRequest
objects in the browser.
◦ JavaScript to make everything happen.
All the available browsers cannot support AJAX. Here
is a list of major browsers that support AJAX.
 Mozilla Firefox 1.0 and above.
 Netscape version 7.1 and above.
 Apple Safari 1.2 and above.
 Microsoft Internet Explorer 5 and above.
 Konqueror.
 Opera 7.6 and above.
AJAX communicates with the server using XMLHttpRequest object. Let's
try to understand the flow of ajax or how ajax works
From the previous diagram 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.
 The keystone of AJAX is 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.
 All modern browsers have a built-in XMLHttpRequest object.

 Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

 Example

var xhttp = new XMLHttpRequest();


Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
Specifies the request

method: the request type GET or POST


open(method,url,async,user,psw) url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
Sends the request to the server
send()
Used for GET requests
Sends the request to the server.
send(string)
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
Property Description
Defines a function to be called when the readyState property
onreadystatechange
changes
Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
readyState
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
Returns the status-number of a request
200: "OK"
status
403: "Forbidden"
404: "Not Found“

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


 To send a request to a server, we use the open() and send()
methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);


xhttp.send();
Method Description
Specifies the request

open(method,url,async) method: the request type GET or POST


url: the 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)


 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.
 A simple GET request:
Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
 In the example above, you may get a cached result. To avoid
this, add a unique ID to the URL:
Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
 If you want to send information with the GET method, add the information to
the URL:
Example
 xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
A simple POST request:
Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
 To POST data like an HTML form, add an HTTP header with
setRequestHeader(). Specify the data you want to send in the send()
method:
Example
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send("fname=Henry&lname=Ford");
 The url parameter of the open() method, is an address
to a file on a server:
xhttp.open("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
 Server requests should be sent asynchronously.
 The async parameter of the open() method should be
set to true:
 xhttp.open("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
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.
function myFunction1(xhttp) {
------
}
function myFunction2(xhttp) {
------
}

loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
Property Description
Defines a function to be called when the readyState property
onreadystatechange
changes
Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
readyState
2: request received
3: processing request
4: request finished and response is ready
Returns the status-number of a request
200: "OK"
status
403: "Forbidden"
404: "Not Found“

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


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.
Server Response Properties

Property Description
responseText get the response data as a string

responseXML get the response data as XML data


 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 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:
Server Response Methods

Method Description
Returns specific header
getResponseHeader() information from the server
resource
Returns all the header information
getAllResponseHeaders()
from the server resource
The getAllResponseHeaders() method returns all header
information from the server response.
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
The getResponseHeader() method returns specific header
information from the server response.
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
 Event is an action or occurrence detected by a program.
 Events can be user actions (clicking a mouse button) or system
occurrences (running out of memory).
 Ajax requests produce a number of different events
 There are two types of events:
◦ Local Events
◦ Global Events
These are callbacks that you can subscribe to within the Ajax
request object, like so:
 beforeSend
This event, which is triggered before an Ajax request is started,
allows you to modify the XMLHttpRequest object
 success
This event is only called if the request was successful (no errors
from the server, no errors with the data).
 error
This event is only called if an error occurred with the request
 complete
This event is called regardless of if the request was successful, or
not. You will always receive a complete callback, even for
synchronous requests.
These events are triggered on the document, calling any handlers
which may be listening. You can listen for these events like so:
 ajaxStart (Global Event)
This event is triggered if an Ajax request is started and no
other Ajax requests are currently running.
 ajaxSend (Global Event)
This global event is also triggered before the request is run.
 ajaxSuccess (Global Event)
This event is also only called if the request was successful.
 ajaxError (Global Event)
This global event behaves the same as the local error event.
 ajaxComplete (Global Event)
This event behaves the same as the complete event and will
be triggered every time an Ajax request finishes.
 ajaxStop (Global Event)
This global event is triggered if there are no more Ajax
requests being processed.
Fetching district names from server on selecting state

form.php dist.php

formstyles.css formscript.js
 MYSQL
◦ DATABASE CREATION
◦ TABLE CREATION
◦ INSERTING ROWS INTO TABLE
◦ UPDATING TABLE ROWS
◦ SELECTING OR RETRIVING DATA FROM THE TABLE
◦ DELETING THE ROWS IN A TABLE

You might also like