Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 8 Ajax

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

Chapter 8 : AJAX

AJAX

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

What is AJAX?
❑AJAX = Asynchronous JavaScript and XML.
❑AJAX is a technique for creating fast and dynamic web
pages.
❑AJAX allows web pages to be updated asynchronously by
exchanging small amounts of data with the server behind
the scenes -, and updating parts of a web page - without
reloading the whole page.
❑ Classic web pages must reload the entire page if the
content should change.

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

Examples of AJAX applications


❑ Google Maps,
❑ Gmail,
❑Youtube, and
❑ Facebook tabs.

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

How AJAX Works

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

AJAX -Based on Internet Standards


AJAX is based on internet standards, and uses a
combination of:
❑XMLHttpRequest object (to exchange data
asynchronously with a server)
❑JavaScript/DOM (to display/interact with the
information)
❑CSS (to style the data)
❑XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!


AMIT2043 Web Systems and Technologies
Chapter 8 : AJAX

AJAX Example

example1

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

How AJAX works?


❑Create an XMLHttpRequest Object
❑Send a Request To a Server
❑Server Response

With AJAX, 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 when the response ready

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

Step 1: Create an XMLHttpRequest Object

❑ XMLHttpRequest object is used to exchange data with a


server by updating 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:
var xmlhttp;
if (window.XMLHttpRequest).
xmlhttp=new XMLHttpRequest();
else //IE5 and IE6 use an ActiveX Object:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
AMIT2043 Web Systems and Technologies
Chapter 8 : AJAX

Step 2: Send a Request To a Server


To send a request to a server, use the open() and send() methods
of the XMLHttpRequest object:
Method Description
open(method, url, Specifies the type of request, the URL, and if the
async) request should be handled asynchronously or not.

method: the type of request: GET or POST

url: the location of the file on the server

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

async: true (asynchronous ) for the XMLHttpRequest


object to behave as AJAX or false (synchronous)
send(string) Sends the request off to the server.
AMIT2043 Web Systems and Technologies
string: Only used for POST requests
Chapter 8 : AJAX
Step 2: Send a Request To a Server

Async=true
When using async=true, specify a function to execute when
the response is ready in the onreadystatechange event:

xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 &&xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.response
Text;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 2: Send a Request To a Server

Async=false
❑ To use async=false, change the third parameter in the open()
method to false:
xmlhttp.open("GET","ajax_info.txt",false);

❑ Using async=false is not recommended, but for a few small


requests this can be ok.
❑ Remember that the JavaScript will NOT continue to execute,
until the server response is ready. If the server is busy or
slow, the application will hang or stop.
❑ Note:When you use async=false, do NOT write an
onreadystatechange function - just put the code after the
send() statement:

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 2: Send a Request To a Server

method :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

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 2: Send a Request To a Server

GET Requests

xmlhttp.open("GET","demo_get.php",true);
xmlhttp.send();

example2

If you want to send information with the GET method,


add the information to the URL:
xmlhttp.open("GET","demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();

example2b

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 2: Send a Request To a Server

POST Requests
To POST data like an HTML form, add an HTTP header with
setRequestHeader(). Specify the data you want to send in
the send() method:

Method Description
setRequestHeader(header,value) Adds HTTP headers to the
request.

header: specifies the header


name
value: specifies the header
value

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 2: Send a Request To a Server

POST Requests

xmlhttp.open("POST","demo_post.php",true);
xmlhttp.send();
example3
xmlhttp.open("POST","ajax_test.php",true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-
urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
example3b

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 2. Send a Request To a Server

XMLHttpRequest Properties
Property Description
onreadystatechange Stores a function (or the name of a function) to
be called automatically each time the readyState
property changes
readyState Holds the status of the XMLHttpRequest.
Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 3. Server Response

The onreadystatechange event


❑When a request to a server is sent, we want to perform
some actions based on the response.
❑The onreadystatechange event is triggered every time
the readyState changes.
❑ onreadystatechange stores the function that will
process the response from the server.
❑The readyState property holds the status of the
XMLHttpRequest.

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 3. Server Response

The onreadystatechange event


When readyState is 4 (server's response is complete) and
status is 200, the response is ready:

xmlhttp.onreadystatechange=function(){
// Get the data from the server's response
if (xmlhttp.readyState==4 &&xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML
=xmlhttp.responseText;
}
}

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 3. Server Response

Server Response
To get the response from a server, use the responseText or
responseXML property of the XMLHttpRequest object.

Property Description
responseText get the response data as a string

responseXML get the response data as XML data

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX
Step 3. Server Response

The responseXML Property


If the response from the server is XML, and you want to
parse it as an XML object, use the responseXML
property:
Request the file cd_catalog.xml and parse the response:
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++) {
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;
example4
AMIT2043 Web Systems and Technologies
Chapter 8 : AJAX

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 on your website,
you should create ONE standard function for creating the
XMLHttpRequest object, and call this for each AJAX task.

❑The function call should contain the URL and what to do


on onreadystatechange (which is probably different for
each call):

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

Using a Callback Function

function myFunction(){
loadXMLDoc("ajax_info.txt",function() {
if (xmlhttp.readyState==4 &&xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseT
ext;
}
});
}
example5

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

AJAX PHP Example

example6
When a user types a character in the input field above,
the function "showHint()" is executed. The function is
triggered by the "onkeyup" event:

The page on the server called by the JavaScript above is an PHP file called
"gethint.php".
Refer to the gethint.php for the details

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

AJAX Database Example

AJAX can be used for interactive communication


with a database.

example7

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

AJAX Database Example


id FirstName LastName Age Hometown Job
1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

 When a user selects a user in the dropdown list above, a


function called "showUser()" is executed. The function
is triggered by the "onchange" event:
 Refer to example7 for details

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

AJAX XML Example


AJAX can be used for interactive communication with an
XML file.
The following example will demonstrate how a web page
can fetch information from an XML file with AJAX:
:Get CD info
example8
example8b

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

AJAX XML Example


The AJAX Server Page
The page on the server used in the example above, is an
XML file called "cd_catalog.xml".
The example9 will demonstrate how a web page can
fetch information from an XML file with AJAX:

CD info will be listed here...

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery - AJAX

Example1

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

What About jQuery and AJAX?


❑jQuery provides several methods for AJAX
functionality.

❑With the jQuery AJAX methods, you can request text,


HTML, XML, or JSON from a remote server using
both HTTP Get and HTTP Post - And you can load the
external data directly into the selected HTML
elements of your web page!

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery load() Method


❑ is a simple, but powerful AJAX method.
❑ loads data from a server and puts the returned data into
the selected element.
Syntax:
$(selector).load(URL,data,callback);

❑ The required URL parameter specifies the URL you wish


to load.
❑ The optional data parameter specifies a set of query
string key/value pairs to send along with the request.
❑ The optional callback parameter is the name of a
function to be executed after the load() method is
completed.

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery load() Method


Content of "demo_test.txt":

<h2>jQuery and AJAX is FUN!!!</h2>


<p id="p1">This is some text in a paragraph.</p>

The following example loads the content of the file


"demo_test.txt" into a specific <div> element:

$("#div1").load("demo_test.txt");

Example1

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery load() Method


❑ It is also possible to add a jQuery selector to the URL
parameter.
❑ The following example loads the content of the
element with id="p1", inside the file "demo_test.txt",
into a specific <div> element:

$("#div1").load("demo_test.txt #p1");
example1b

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery load() Method


❑The following example displays an alert box after the
load() method completes.
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,
xhr){
if(statusTxt=="success")
alert("External content loaded successfully!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});

example1c
AMIT2043 Web Systems and Technologies
Chapter 8 : AJAX

jQuery load() Method


❑The optional callback parameter specifies a callback
function to run when the load() method is completed.
The callback function can have different parameters:
❑responseTxt - contains the resulting content if the call
succeed
❑statusTXT - contains the status of the call
❑xhr - contains the XMLHttpRequest object

jQuery AJAX Reference:


http://www.w3schools.com/jquery/jquery_ref_ajax.asp
AMIT2043 Web Systems and Technologies
Chapter 8 : AJAX

jQuery $.get() Method


The $.get() method requests data from the server with an
HTTP GET request.
Syntax:
$.get(URL,callback);

❑The required URL parameter specifies the URL you wish


to request.
❑The optional callback parameter is the name of a
function to be executed if the request succeeds.
❑The following example uses the $.get() method to
retrieve data from a file on the server:

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery $.get() Method


$("button").click(function(){
$.get("demo_test.php",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
example2
The first parameter of $.get() is the URL we wish to
request ("demo_test.php").
The second parameter is a callback function. The first
callback parameter holds the content of the page
requested, and the second callback parameter holds
the status of the request.

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery $.post() Method


The $.post() method requests data from the server using an
HTTP POST request.
$.post(URL,data,callback);
Syntax:

❑ The required URL parameter specifies the URL you wish


to request.
❑ The optional data parameter specifies some data to send
along with the request.
❑ The optional callback parameter is the name of a
function to be executed if the request succeeds.

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery $.post() Method

$("button").click(function(){
$.post("demo_test_post.asp",
{
name:"Donald Duck",
city:"Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
example2b

AMIT2043 Web Systems and Technologies


Chapter 8 : AJAX

jQuery $.post() Method

❑The first parameter of $.post() is the URL we wish to


request ("demo_test_post.php").
❑Then we pass in some data to send along with the
request (name and city).
❑The ASP script in "demo_test_post.php" reads the
parameters, process them, and return a result.
❑The third parameter is a callback function. The first
callback parameter holds the content of the page
requested, and the second callback parameter holds
the status of the request.
AMIT2043 Web Systems and Technologies
Chapter 8 : AJAX

The End

AMIT2043 Web Systems and Technologies

You might also like