3 April 2021
Developing Interactive Web
Applications
AJAX –AJAX calls - XML http – request – response – AJAX
with JSON- Data Formats – AJAX with Database –
AJAX Processing Server Response - AJAX Security
Dr.V.Mareeswari
Assistant Professsor(Sr)
School of Information Technology and Engineering
VIT,Vellore
Cabin No:SJT 210-A30
2 Dr. V.Mareeswari / AP(Sr) / SITE / VIT
Introduction to AJAX
AJAX = Asynchronous JavaScript and XML.
Comparison
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. This means that it is
possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if
the content should change.
Examples of applications using AJAX: Google Maps, Google Suggest, Gmail,
Youtube, Flickr, and Facebook tabs.
AJAX meant to increase the web page's interactivity, speed, and
usability.
Ajax is not a programming language or a tool, but a concept. Ajax is
a client-side script that communicates to and from a server/database
3
without the need for a postback or a complete page refresh.
V.Mareeswari / AP (Sr) / SITE 4/3/2021 4 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 1
3 April 2021
How AJAX works? AJAX is based on Internet Standards
1. XMLHttpRequest object (to exchange data asynchronously with a
server)
2. JavaScript/DOM (to display/interact with the information)
3. CSS (to style the data)
4. XML (often used as the format for transferring data)
Note: AJAX applications are browser- and platform-independent!
AJAX can be used for interactive communication with a database and an
XML file .
5 V.Mareeswari / AP (Sr) / SITE 4/3/2021 6 V.Mareeswari / AP (Sr) / SITE 4/3/2021
<html> <head> <script>
C:/wamp/www/first
function loadXMLDoc(){
Sample Code var xmlhttp;
AJAX.html
<!DOCTYPE html> if (window.XMLHttpRequest)
<html> <body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div> xmlhttp=new XMLHttpRequest();
<button type="button" onclick="loadXMLDoc()">Change xmlhttp.onreadystatechange=function()
Content</button> {
</body></html> <head> if (xmlhttp.readyState==4 && xmlhttp.status==200)
<script>
function loadXMLDoc() document.getElementById("myDiv").innerHTML=xmlhttp.response
{ Text; }
.... AJAX script goes here ... xmlhttp.open("GET","AJAX_TextFile.txt",true);
}
</script> xmlhttp.send(); } </script> </head> <body>
7 V.Mareeswari / AP (Sr) / SITE </head> 4/3/2021 8 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 2
3 April 2021
Output
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change
Content</button>
</body> </html>
C:/wamp/www/AJAXTextFile.txt
AJAX is not a programming language.
AJAX is a technique for accessing web servers from a web page.
AJAX stands for Asynchronous JavaScript And XML.
9 V.Mareeswari / AP (Sr) / SITE 4/3/2021 10 V.Mareeswari / AP (Sr) / SITE 4/3/2021
The XMLHttpRequest Object Send a Request To a Server
xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send();
The XMLHttpRequest object is used to exchange data with a server
behind the scenes. This means that it is possible to update parts of a web xmlhttp.open("GET","demo.asp?t=" + Math.random(),true);
page, without reloading the whole page. xmlhttp.open("GET","demo.asp?fname=Henry&lname=Ford",true);
var xmlhttp; The file can be any kind of file, like .txt and .xml, or server scripting
if (window.XMLHttpRequest) files like .asp and .php (which can perform actions on the server before
{// code for IE7+, Firefox, Chrome, Opera, Safari sending the response back).
xmlhttp=new XMLHttpRequest(); Method Description
} Specifies the type of request, the URL, and if the
else request should be handled asynchronously or not.
{// code for IE6, IE5 open(method,url,async) method: the type of request: GET or POST
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); url: the location of the file on the server
} async: true (asynchronous) or false (synchronous)
Sends the request off to the server.
send(string)
11 V.Mareeswari / AP (Sr) / SITE 4/3/2021 12 V.Mareeswari / AP (Sr) / SITEstring: Only used for POST requests 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 3
3 April 2021
Asynchronous - True or False?
xmlhttp.onreadystatechange=function()
Sending asynchronous requests is a huge improvement for web {
developers. Many of the tasks performed on the server are very time if (xmlhttp.readyState==4 && xmlhttp.status==200)
consuming. Before AJAX, this operation could cause the application {
to hang or stop. document.getElementById("myDiv").innerHTML=xmlhttp.res
With AJAX, the JavaScript does not have to wait for the server ponseText;
response, but can instead: }
}
execute other scripts while waiting for server response
xmlhttp.open("GET","ajax_info.txt",true);
deal with the response when the response ready
xmlhttp.send();
13 V.Mareeswari / AP (Sr) / SITE 4/3/2021 14 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Async=false AJAX - Server Response
Using async=false is not recommended, but for a few small
Property Description
requests this can be ok.
Remember that the JavaScript will NOT continue to execute, until responseText get the response data as a string
the server response is ready. If the server is busy or slow, the
application will hang or stop.
responseXML get the response data as XML data
Note: When you use async=false, do NOT write an
onreadystatechange function - just put the code after the send() If the response from the server is not XML, use the responseText
statement: property.
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send(); document.getElementById("myDiv").innerHTML
document.getElementById("myDiv").innerHTML=xmlhttp.respo
nseText;
=xmlhttp.responseText;
15 V.Mareeswari / AP (Sr) / SITE 4/3/2021 16 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 4
3 April 2021
If the response from the server is XML, and you want to parse it as an
The onreadystatechange event
XML object, use the responseXML property: When a request to a server is sent, we want to perform some
Request the file cd_catalog.xml and parse the response: actions based on the response.
The onreadystatechange event is triggered every time the
xmlDoc=xmlhttp.responseXML; readyState changes.
txt=“ “; The readyState property holds the status of the XMLHttpRequest.
x=xmlDoc.getElementsByTagName("ARTIST"); Three important properties of the XMLHttpRequest object:
for (i=0;i<x.length;i++)
{ xmlhttp.onreadystatechange=function() {
txt=txt + x[i].childNodes[0].nodeValue + "<br>"; if (xmlhttp.readyState==4 && xmlhttp.status==200) {
} document.getElementById("myDiv").innerHTML=
document.getElementById("myDiv").innerHTML=txt; xmlhttp.responseText; } }
Note: The onreadystatechange event is triggered five times (0-4), one
time for each change in readyState.
17 V.Mareeswari / AP (Sr) / SITE 4/3/2021 18 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Property Description Server Response Methods - getAllResponseHeaders()
<!DOCTYPE html><html><body><h2>The XMLHttpRequest
Stores a function (or the name of a function) to Object</h2><p>The getAllResponseHeaders() function returns all
onreadystatechange be called automatically each time the readyState the header information of a resource, like length, server-type, content-
property changes type, last-modified, etc:</p><p id="demo"></p>
Holds the status of the XMLHttpRequest. <script>var xhttp = new XMLHttpRequest();
Changes from 0 to 4: xhttp.onreadystatechange = function() {
0: request not initialized
if (this.readyState == 4 && this.status == 200) {
readyState 1: server connection established
2: request received document.getElementById("demo").innerHTML =
3: processing request this.getAllResponseHeaders();
4: request finished and response is ready }};
200: "OK" xhttp.open("GET", "ajax_info.txt", true);
status
404: Page not found xhttp.send();</script></body></html>
19 V.Mareeswari / AP (Sr) / SITE 4/3/2021 20 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 5
3 April 2021
Server Response Methods - getResponseHeader()
<!DOCTYPE html><html><body><h2>The XMLHttpRequest
Output Object</h2><p>The getResponseHeader() function is used to
return specific header information from a resource, like length, server-
type, content-type, last-modified, etc:</p>
<p>Last modified: <span id="demo"></span></p><script>
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);
21 V.Mareeswari / AP (Sr) / SITE 4/3/2021 xhttp.send();</script></body></html> 4/3/2021
V.Mareeswari / AP (Sr) / SITE
AJAX with JSON
<html><head><script type = "text/javascript">
Output function loadJSON(){
var data_file = "http://www.tutorialspoint.com/json/data.json";
//var data_file = "data.json";
var http_request = new XMLHttpRequest();
try{ // Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){ // Internet Explorer Browsers
try{ http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){ // Something went wrong
alert("Your browser broke!"); return false;
23 V.Mareeswari / AP (Sr) / SITE 4/3/2021 }}}
24 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 6
3 April 2021
http_request.onreadystatechange = function(){ <body>
if (http_request.readyState == 4 ){ <h1>Cricketer Details</h1>
// Javascript function JSON.parse to parse JSON data <table class = "src">
var jsonObj = JSON.parse(http_request.responseText); <tr><th>Name</th><th>Country</th></tr>
// jsonObj variable can be accessed <tr><td><div id = "Name">Sachin</div></td>
document.getElementById("Name").innerHTML = <td><div id = "Country">India</div></td></tr></table>
jsonObj.name;
<div class = "central">
document.getElementById("Country").innerHTML =
<button type = "button" onclick = "loadJSON()">Update
jsonObj.country;
Details </button> </div> </body></html>
}}
http_request.open("GET", data_file, true);
http_request.send(); } </script> </head>
25 V.Mareeswari / AP (Sr) / SITE 4/3/2021 26 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Exercises
The following example will demonstrate how a web page can
communicate with a web server while a user type characters in an
input field:
Start typing a name in the input field below:
First name: a
Suggestions: Anna , Amanda
Start typing a name in the input field below:
First name: m
Suggestions: no suggestion
27 V.Mareeswari / AP (Sr) / SITE 4/3/2021 28 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 7
3 April 2021
<!DOCTYPE html><html><head><script> <?php
function showHint(str){ ajax_suggest.html $a=array("Akila","Arun","Abilash","Bala","Cindrella","Cindy","Danil",
var xmlhttp;
if (str.length==0) { "Florida","Marees","Shree");
document.getElementById("txtHint").innerHTML=""; $q=$_REQUEST["q"]; $hint="";
return; } if ($q !== "") // lookup all hints from array if $q is different from ""
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(); } { $q=strtolower($q); $len=strlen($q);
xmlhttp.onreadystatechange=function() { foreach($a as $name)
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } }
{ if (stristr($q, substr($name,0,$len))) gethint.php
xmlhttp.open("GET","gethint.php?q="+str,true); { if ($hint==="")
xmlhttp.send();}</script></head><body> { $hint=$name; }
<h3>Start typing a name in the input field below:</h3>
<form action="">
else
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> { $hint .= ", $name"; } } } }
</form>
<p>Suggestions: <span id="txtHint"></span></p> </body></html>
echo $hint==="" ? "no suggestion" : $hint;?>
29 V.Mareeswari / AP (Sr) / SITE 4/3/2021 30 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Exercise
AJAX can be used for interactive communication with a database and an
XML file .
31 V.Mareeswari / AP (Sr) / SITE 4/3/2021 32 V.Mareeswari / AP (Sr) / SITE 4/3/2021
Dr.V.Mareeswari / AP(Sr) / SITE 8
3 April 2021
<!DOCTYPE html> <html><head>
jQuery ajax() Method
<meta name="viewport" content="width=device-width" /><script
The $.ajax() method provides core functionality of Ajax in jQuery. It sends src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js>
asynchronous HTTP requests to the server. </script>
Syntax: $.ajax(url); $.ajax(url,[options]); <script type="text/javascript">
url:A string URL to which you want to submit or retrieve the data $(document).ready(function () {
options: Configuration options for Ajax request. An options parameter can $('#ajaxBtn').click(function(){
be specified using JSON format.This parameter is optional. $.ajax('/jquery/getdata', // request url
xhr:A callback for creating the XMLHttpRequest object. { success: function (data, status, xhr) { // success callback function
success:A callback function to be executed when Ajax request succeeds. $('p').append(data); } }); }); });
data:A data to be sent to the server. It can be JSON object, string or array. </script></head><body>
<h1> jQuery ajax() demo Retrive data from server </h1>
timeout:A number value in milliseconds for the request timeout.
<input type="button" id="ajaxBtn" value="Send Ajax request" />
<p> </p></body></html>
33 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 34 Dr. V.Mareeswari / AP(Sr) / SITE / VIT
$(document).ready(function () { $(document).ready(function () {
$('#ajaxBtn').click(function(){ $('#ajaxBtn').click(function(){
$.ajax('/jquery/getjsondata', { $.ajax('/jquery/submitData', {
dataType: 'json', // type of response data type: 'POST', // http method
timeout: 500, // timeout milliseconds data: { myData: ' This is mareeswari data.' }, // data to submit
success: function (data,status,xhr) { // success callback function success: function (data, status, xhr) {
$('p').append(data.firstName + ' ' + data.middleName + ' ' + $('p').append('status: ' + status + ', data: ' + data); },
data.lastName); }, error: function (jqXhr, textStatus, errorMessage) {
error: function (jqXhr, textStatus, errorMessage) { // error callback $('p').append('Error: ' + errorMessage); }});}); });
$('p').append('Error: ' + errorMessage); }}); });});
In the options parameter, we have specified a type
option as a POST, so ajax() method will send http
POST request. Also, we have specified data option
as a JSON object containing data which will be
35 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 36 Dr. V.Mareeswari / AP(Sr) / SITE submitted
/ VIT to the server.
Dr.V.Mareeswari / AP(Sr) / SITE 9
3 April 2021
The jQuery get() method sends asynchronous http GET request to the
server and retrieves the data. Ajax will not die. Traditional Ajax refers to
Syntax: $.get(url, [data],[callback]); XMLHttpRequest (XHR), Future It has now been
The jQuery post() method sends asynchronous http POST request to the replaced by fetch.
server to submit the data to the server and get the response.
Syntax: $.post(url,[data],[callback],[type]);
The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.
The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.
Syntax: $.load(url,[data],[callback]);
37 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 38 Dr. V.Mareeswari / AP(Sr) / SITE / VIT
AJAX Security
AJAX Security AJAX-based Web applications use the same server-side
security schemes of regular Web applications.
You specify authentication, authorization, and data protection requirements
in your web.xml file (declarative) or in your program (programmatic).
AJAX-based Web applications are subject to the same security threats as
regularWeb applications.
AJAX Security: Client Side
JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for
inferring server-side weaknesses.
JavaScript code is downloaded from the server and executed ("eval") at the
client and can compromise the client by mal-intended code.
Downloaded JavaScript code is constrained by the sand-box security model
and can be relaxed for signed JavaScript.
39 Dr. V.Mareeswari / AP(Sr) / SITE / VIT
Dr.V.Mareeswari / AP(Sr) / SITE 10