SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
PREFACE


This tutorial is free only for educational purpose. This tutorial is not full; it helps you to just
know the subject. This is good to start a beginning.

We have collected study material also from out-sources which is not meant for any sales
value. This tutorial is also not publishing on any commercial web site, society or any other
area where it shows commercial.

Shweta SofTech India erstwhile Shim SofTech India is established on 26th Jan’2006 for
encouraging free I.T. education in India. We hope you will get a worth from this book.

For any further query please write to us: info@shwetasoftech.com


With many thanks,

Shimona Arora
shim@shimsoftech.com
AJAX: ........................................................................................................................................ 1

   WHAT STANDS FOR AJAX: ........................................................................................................... 2
   AJAX – ENABLED WEB-PAGE: ARCHITECTURE ................................................................................ 3
   AJAX – LIFE CYCLE ..................................................................................................................... 3
   AJAX – WEB STANDARD .............................................................................................................. 4
   WHEN DO I START USING AJAX? ..................................................................................................... 4
   HOW DOES AJAX WORK? ............................................................................................................... 4
           THE READYSTATE PROPERTY .........................................................................................................5
           THE RESPONSETEXT PROPERTY......................................................................................................5
           AJAX - SENDING A REQUEST TO THE SERVER ...............................................................................5
           CROSS-BROWSER ISSUES ..................................................................................................................5
           EXERCISE:..........................................................................................................................................6

AJAX: IMPLEMENTATION ......................................................................................................... 7

           SIMPLE LOGIN ACTIVITY WITHOUT USE OF AJAX:..........................................................................7

       APPLICATION WITH AJAX: ............................................................................................... 10
           LOGIN-AJAX.HTML ......................................................................................................................... 10
           CLIENTACTION-AJAX.JS................................................................................................................ 11
           GETID.ASP....................................................................................................................................... 12
           EXPLANATION OF AJAX APPLICATION ....................................................................................... 13
           USING, AJAX, YOU CAN ALSO SOLVE ALL OTHER PROBLEMS RELATED TO DATABASES, XML
           ETC.EXERCISE: ............................................................................................................................... 13
           EXERCISE:....................................................................................................................................... 14
1                                                                          AJAX-Learning Tutorial




AJAX:
When we started this topic many questions revolved around our minds. What is Ajax? What it
does? Why we need to use it? And many more.

We are here to solve all those questions. Lets starts with a simple step. First to know exactly
what is it? I will tell you the full meaning of the Ajax in next lines but now let me explain
that:

Whenever we need some information at client side, what is happened or what did we do? In
Simple words, we just send request from browser to server and get the response. Yes, this is
all known as round trip. But, did you notice in this, what?

Generally, when we sent a request to server from browser our entire page did get refresh and
each and every page element reload the page. Or in other words lets take it in following
examples:

<head>
<title>Login.html</title>
</head>
<body>
<form name="myForm">
<table>
<tr>
<td><b>Login Id : </b> <input type="text" name="myLogin" /></td>
</tr>
<tr>
<td><b>Password: </b> <input type="text" name="myPass"     /></td>
</tr>
</table>
<p>
<input type="submit" name="myDetails" value="Login" />
</p>

</form>
</body>
</html>

The above html page looks like as:




                                                  Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                                                            2


Now, what happens when user enter Login id simply nothing happens until he or she submit
the request by pressing Login button. As soon as login button presses a request to server for
checking the existence of the Login Id in databases or in any other source where it is located.
It means whenever login button press, a request passes to the server and response gets at
browser site by refreshing or reloading the entire page.

Think about that page, form which contains numerous elements present on it. Isn’t it slow
down the speed of the web or page on every request? Because, every time page will be
reloaded its element.

To redeem this issue we use AJAX. With the help of Ajax we don’t need to refresh entire
page to fulfill our request.


WHAT STANDS FOR AJAX:
The brief terminology of the web page is cleared, also the request and response is understand.
Now, let’s start with the meaning of AJAX:

AJAX: ASYNCHRONOUS JAVASCRIPT AND XML

To define it more deeply lets first understand the Synchronous and Asynchronous.

Suppose, you want to know the existence of entered login-id (sometimes, user-id and
login-id behaves synonymous but in practically user-id is the
identification of the user who is permit to obtain or use the
services to a particular unit or page, in the other hand Login-id
ensures the entrance of a particular Login-id holder but it doesn’t
mean that he or she may entitle to obtain the services. Because in
some cases where security matters upto its hike, different kinds of
user-id’s provided to different persons under same login-id. Suppose,
you have a card to enter in office premises, you punch the card it
means you logins then push back the card and enter your personal PIN
or identification number with your password, all this is about Login-
Id and User-ID) in a registration form. It requires when new user want to register for the
services and he or she fills the registration form. At this stage what happens? Normally,
request goes to server and response retrieve to browser about the existence of the entered
Login Id. Our entire rest action or work is blindly depend upon this action, it means we are
unable to do or process an further step until we retrieve or get the response from server. This
task is known or called as Synchronous. While in the other hand the contents of entire page or
some part-contents of page need the same process but out other task or work is not affect from
this, is called asynchronous task(s).

In general, simple and in raw words you can compare both with the two way and one-way
communication. In one we have to wait the response to go ahead for next step while in other
we may proceed for the further step.




Shim SofTech India (email: info@shimsoftech.com)
3                                                                                                        AJAX-Learning Tutorial


With the keen light of above discussion, now we are able to declare the exactly what is
AJAX?

AJAX is a web technology which is favorable to dynamic and rich web control/elements. It is
a combination of JavaScript and XML, favoring asynchronously communication.



AJAX – ENABLED WEB-PAGE: ARCHITECTURE
It’s a technology and not a new to developers It is using from 2005 in Google services like
Google maps and Google suggests.

With AJAX, your JavaScript can communicate directly with the server, using the JavaScript
XMLHttpRequest object. With this object, your JavaScript can trade data with a web server,
without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web
server, allowing web pages to request small bits of information from the server instead of
whole pages.

Ajax enables a new architecture. The important parts of this architecture are:

     1. Small Server Side Events: Now components in a web application can make small
        requests back to a server, get some information, and tweak the page that is viewed by
        changing the DOM. No full page refresh.
     2. Asynchronous: Requests posted back to the server don’t cause the browser to block.
        The user can continue to use other parts of the application, and the UI can be updated
        to alert the user that a request is taking place.
     3. onAnything: We can talk back to a server based on almost anything the user does.
        Modern browsers trap most of the same user events that the operating system allows:
        mouse clicks, mouse overs, keypresses, etc. Any user event can trigger an
        asynchronous request.



AJAX – LIFE CYCLE
     1. User makes initial request against a given URL
     2. Server returns original HTML page
     3. Browser renders page as in-memory DOM tree
     4. User activity causes subsequent request against another URL asynchronously, leaving
        existing DOM tree untouched
     5. Browser returns data to a callback function inside the existing page
     6. Browser parses result and updates in-memory DOM with the new data, which is then
        reflected on screen to the user (the page is redrawn, but not "refreshed")

Imp: The AJAX technique makes Internet applications smaller, faster and more user-friendly. AJAX is a browser technology independent
of web server software.




                                                                      Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                                                             4



AJAX – WEB STANDARD
AJAX is based on the following web standards:
      • JavaScript
      • XML
      • HTML
      • CSS
The web standards used in AJAX are well defined, and supported by all major browsers.
AJAX applications are browser and platform independent.



WHEN DO I START USING AJAX?
As already mentioned above that Ajax is very easy and based on Web Standard technology.
So, if you know or have the idea of JavaScript, Xml, Html, CSS then you can start Ajax today
from now.

If you are unaware from the above technologies then no need to be depressed just take a
beneath sitting for above topics and return back here to learn and know about the exiting and
more powerful technology called AJAX.


HOW DOES AJAX WORK?
It’s the first question in my mind when I have started to read Ajax. As it is already discussed
that this is a Technology of web based so, it also works same as other technologies work.

Let’s start in simple terminology: to do start any web application we need following(s):
    • Platform or Form to enter user data
    • Server side scripting language
    • Client Side scripting language

In previous mentioned example titled login.html provides us a form to enter information.
Now for other two i.e. sever side and client side languages first, we need to understand
following in more details:

In traditional JavaScript coding, if you want to get any information from a database or a file
on the server, or send user information to a server, you will have to make an HTML form and
GET or POST data to the server. The user will have to click the "Submit" button to send/get
the information, wait for the server to respond, and then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web
applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript
XMLHttpRequest object With an HTTP request, a web page can make a request to, and get a
response from a web server - without reloading the page. The user will stay on the same page,
and he or she will not notice that scripts request pages, or send data to a server in the
background.




Shim SofTech India (email: info@shimsoftech.com)
5                                                                          AJAX-Learning Tutorial


By using the XMLHttpRequest object, a web developer can update a page with data from the
server after the page has loaded!

The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 /
Firefox, Opera 8+, and Netscape 7.

The readyState Property
The readyState property holds the status of the server's response. Each time the readyState
changes, the onreadystatechange function will be executed. Here are the possible values for
the readyState propery:

              State                               Description
                0          The request is not initialized
                1          The request has been set up
                2          The request has been sent
                3          The request is in process
                4          The request is complete


The responseText Property
The data sent back from the server can be retrieved with the response Text property. This
property assures the responded data of our request.


AJAX - Sending a Request to the Server
To send off a request to the server, we use the open() method and the send() method.

The open() method takes three arguments. The first argument defines which method to use
when sending the request (GET or POST). The second argument specifies the URL of the
server-side script. The third argument specifies that the request should be handled
asynchronously.

The send() method sends the request off to the server.

Cross-Browser Issues
The web page painted with Ajax technology at least one rather severe cross-browser
imitation. The way it initializes the XMLHttpRequest object will only function on Mozilla
1.0+ and Safari 1.2+; it does not function on Internet Explorer. On IE 5.0+, the way to create
it is (discussed in following example:




                                                  Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                                                        6


var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;

The simple method is to obey the Try-Catch rule to initiate the same. In we have declared a
variable named xmlHttp and then creating an object of XMLHttpRequest() using try-catch
block. This is the universal block which is used in everywhere Ajax use.

Exercise:
Let’s revise
    1. What is Ajax?
    2.   How Ajax web based Technology?
    3.   Write few line son Ajax Architecture defining life cycle of an Ajax web page
    4. How does Ajax work?
    5.   How we can detect browser using try-catch bock?
    6.   Define four ready states of Ajax.
    7.   What are send() and open(0 method(s)?
    8. What are cross-browsers issue?
    9.   What do you mean by round trip?
    10. Define Login-Id and User-Id myth




Shim SofTech India (email: info@shimsoftech.com)
7                                                                          AJAX-Learning Tutorial




AJAX: IMPLEMENTATION
In this head we will consider some practical exercise which favoring implementation of the
Ajax:

Our entire topic is depends upon the Registration and Login issues:


Simple Login activity without use of Ajax:

Consider our login.html example; let’s modify it with the use of JavaScript:
Login.html

<head>
<title>Login.html</title>
<script src="clientaction.js">

</Script>
</head>
<body onLoad="set(this.form);">
<form name="myForm">
      <table>
      <tr>
        <td><b>Login Id    : </b> <input type="text" name="myLogin"
size="40" onBlur="checklen(this.form);" /></td>
      </tr>
      <tr>
            <td><b>Password: </b> <input type="text" name="myPass"
size="40"   /></td>
      </tr>
      </table>
      <p>
            <input   type="submit"   name="myDetails" value="Login"
onClick="verify(this.form);" />
      </p>

</form>
</body>
</html>




                                                  Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                                    8


Clientaction.js
// JavaScript Document
//File Name - clientaction.js
<!-- The function verify() chekd whetehr appropriate information -->
<!-- filled in all the elements. I any elements is left empty, an
alert() box-->
<!--is displayed information the user to fill in the empty element.
the code-->

function verify(form)
{
      for (i=0; i<=1;i++)
      {
            if (document.forms[0].elements[i].value=="")
            {
                  alert("Please     fill    in     the            "   +
document.forms[0].elements[i].name +" field");
                  document.forms[0].elements[i].focus();
                  return(false);
            }



        }

        return(true);
}


<!--Sets the focus on the first element when the form loade-->

function set(form)
{
      document.forms[0].elements[0].focus()
}

<!--he function checklen() checks that the length of name and-->
<!--email address does not exceed 30 character-->

function checklen(form)
{
      for(i=0;i<=1;i++)
      {
            val=document.forms[0].elements[i].value;
            len=val.length;

                  if(len>30)
                  {
                        alert("Value exceeds 30 characters");
                        document.forms[0].elements[i].value="";
                        document.forms[0].elements[i].focus();
                  }
        }
}




Shim SofTech India (email: info@shimsoftech.com)
9                                                                          AJAX-Learning Tutorial




With the help of above change, we can just enable client interaction but till now our problem
is arisen as the same.




Only some or fewer errors made at browser side will be displayed. But our main motive is
asynchronous communication. The above is done when we submit the form. It means that the
whole document first submit and then gets the response from the server. It will take time.

Now, not wasting the time lets start our Ajax application.




                                                  Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                                  10



Application with AJAX:

Login-ajax.html

<head>
<title>Login.html</title>
<script src="clientaction-ajax.js">

</Script>
</head>
<body>
<form name="myForm">
      <table>
      <tr>
        <td><b>Login Id    : </b> <input type="text" name="myLogin"
size="40" onkeyup="showID(this.value)" /></td>
      </tr>
      <tr>
            <td><b>Password: </b> <input type="text" name="myPass"
size="40"   /></td>
      </tr>
      </table>
      <p>
            <font                    color="Blue"><b></b></font><span
id="txtid"></span></p>
      </p>

</form>
</body>
</html>




Shim SofTech India (email: info@shimsoftech.com)
11                                                           AJAX-Learning Tutorial


clientaction-ajax.js

var xmlHttp
function showID(str)
{
if (str.length==0)
{
document.getElementById("txtid").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getid.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtid").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}




                                    Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                               12


getid.asp

<%
response.expires=-1
dim a(36)
'Fill up array with names
a(1)="Anu"
a(2)="Mohan"
a(3)="Anil"
a(4)="Sunil"
a(5)="Vinita"
a(6)="Subha"
a(7) ="Gaurav"
a(8)="Neetu"
a(9)="Rachita"
a(10)="Inga"
a(11)="Ricky"
a(12)="Rekha"
a(13)="Linda"
a(14)="Nina"
a(15)="Ophelia"
a(16)="Petunia"
a(17)="Amanda"
a(18)="Raquel"
a(19)="Cindy"
a(20)="Doris"
a(21)="Eve"
a(22)="Evita"
a(23)="Sunniva"
a(24)="Tove"
a(25)="Unni"
a(26)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
a(31)="Shimona"
a(32)="Swati"
a(33)="Arun"
a(34)="Shikha"
a(35)="Shweta"
a(36)="Anu"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 36
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if

if hint="" then
response.write("<b>This Login Id is invalid or doesn't exist</b>")



Shim SofTech India (email: info@shimsoftech.com)
13                                                                          AJAX-Learning Tutorial


else
response.write("<b>Available user(s): </b>" & hint)
end if
%>

Explanation of Ajax Application

Above example is explained as follow:
   1. A Form is created, in which login id is entered
   2. In the event of keyup of the field showed() function calls by passing field’s value
   3. In the function we have confirmed the browser and then send the request using open()
       and send () method(s).




     4. Get the text by checking onreadystatechange.
     5. In the other hand in file getid.asp which is written in server side scripting language,
        we have declared an array of some id’s.




     6. Now, as soon as we write in the Login Id field, available logins display in the bottom
        of the form and if not available then message appears.
     7. This all is done using asynchronous communication.


Using, Ajax, you can also solve all other problems related to databases, xml etc.




                                                   Shim SofTech India (email: info@shimsoftech.com)
AJAX-Learning Tutorial                                                                            14


Exercise:
Implement ajax in following(s):

    1. Create a registration form which contains Login-ID, First Name, Last Name,
       Password, Retype Password field(s). During the registration confirm existence of
       entered Login-Id. The database stores in file user.mdb
    2. In continuation to above create a Login-form which permits login-id which is stored
       in user.xml file (the login id’s are same as stored in user.mdb file). Here using Ajax,
       compare the password. On successful login show the welcome window showing the
       Full Name and id of the user.
    3. Create a text file named collection.txt which contains the information of
       abbreviations, like- Ajax: Asynchronous JavaScript and Xml, HTML: ypertext
       MarkUp Language, ASP: Active Server Pages, PHP: PHP Hypertext Preprocessor
       etc. Create a form where user enter any words then retrieve the information related to
       that word (if exists), if information of entered word is not found in the collection ask
       user to enter the proper definition of that words by showing Id and definition field(s).
       remember ID and definition field are like AJAX (ID) and Asynchronous JavaScript
       and Xml (definition).
    4. Recreate above application using database(s) instead of text file(s).



To obtain the full collection of codes please write to us: infor@shwetasoftech.com under
subject: Ajax-examples. These all are free and anyone can use these examples as these ae
meant for only educational purpose.




Shim SofTech India (email: info@shimsoftech.com)

Contenu connexe

Tendances

Service Workers and Their Role in Apps
Service Workers and Their Role in AppsService Workers and Their Role in Apps
Service Workers and Their Role in AppsTasha Penwell
 
Amazon Web Services sign-up
Amazon Web Services sign-upAmazon Web Services sign-up
Amazon Web Services sign-upSimone Brunozzi
 
Word press security guard
Word press security guardWord press security guard
Word press security guardAdrianoViana25
 
Advanced Error Handling Strategies for ColdFusion
Advanced Error Handling Strategies for ColdFusion Advanced Error Handling Strategies for ColdFusion
Advanced Error Handling Strategies for ColdFusion Mary Jo Sminkey
 
Top Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.NetTop Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.Netalsmola
 
Headway Design Two 0
Headway Design Two 0Headway Design Two 0
Headway Design Two 0crackmaker00
 

Tendances (6)

Service Workers and Their Role in Apps
Service Workers and Their Role in AppsService Workers and Their Role in Apps
Service Workers and Their Role in Apps
 
Amazon Web Services sign-up
Amazon Web Services sign-upAmazon Web Services sign-up
Amazon Web Services sign-up
 
Word press security guard
Word press security guardWord press security guard
Word press security guard
 
Advanced Error Handling Strategies for ColdFusion
Advanced Error Handling Strategies for ColdFusion Advanced Error Handling Strategies for ColdFusion
Advanced Error Handling Strategies for ColdFusion
 
Top Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.NetTop Ten Tips For Tenacious Defense In Asp.Net
Top Ten Tips For Tenacious Defense In Asp.Net
 
Headway Design Two 0
Headway Design Two 0Headway Design Two 0
Headway Design Two 0
 

En vedette

Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorialoscon2007
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohanWebVineet
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programminghchen1
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)maditabalnco
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsBarry Feldman
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome EconomyHelge Tennø
 

En vedette (7)

Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post Formats
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Similaire à Ajax learning tutorial

Jobportal 130815001657-phpapp01
Jobportal 130815001657-phpapp01Jobportal 130815001657-phpapp01
Jobportal 130815001657-phpapp01Areef Khan
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end appsZohar Arad
 
ABC Online Direct store software architecture using SOA (Service Oriented Arc...
ABC Online Direct store software architecture using SOA (Service Oriented Arc...ABC Online Direct store software architecture using SOA (Service Oriented Arc...
ABC Online Direct store software architecture using SOA (Service Oriented Arc...Akash Mhankale
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Clarence Ngoh
 
Amazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS New
Amazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS NewAmazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS New
Amazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS NewCatherine Aguirre
 
Working on Tasks in Microsoft Project Web Access
Working on Tasks in Microsoft Project Web AccessWorking on Tasks in Microsoft Project Web Access
Working on Tasks in Microsoft Project Web AccessDavid J Rosenthal
 
A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...
A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...
A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...HakTrak Cybersecurity Squad
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applicationsdominion
 
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer scriptMaker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer scriptSwarnkar Rajesh
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S GuideAlicia Buske
 
Sending the data already gathered from the client to the Server
Sending the data already gathered from the client to the ServerSending the data already gathered from the client to the Server
Sending the data already gathered from the client to the Serverhussam242
 
HDFC banking system SRS Document
HDFC banking system  SRS DocumentHDFC banking system  SRS Document
HDFC banking system SRS DocumentNavjeetKajal
 

Similaire à Ajax learning tutorial (20)

Ajax part i
Ajax part iAjax part i
Ajax part i
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Jobportal 130815001657-phpapp01
Jobportal 130815001657-phpapp01Jobportal 130815001657-phpapp01
Jobportal 130815001657-phpapp01
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
Net banking
Net banking Net banking
Net banking
 
Ajax and PHP
Ajax and PHPAjax and PHP
Ajax and PHP
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
 
ABC Online Direct store software architecture using SOA (Service Oriented Arc...
ABC Online Direct store software architecture using SOA (Service Oriented Arc...ABC Online Direct store software architecture using SOA (Service Oriented Arc...
ABC Online Direct store software architecture using SOA (Service Oriented Arc...
 
Major project report
Major project reportMajor project report
Major project report
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)
 
Amazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS New
Amazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS NewAmazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS New
Amazon Kindle Paperwhite 4G Vs 2017 3G Model A Look At WhatS New
 
Working on Tasks in Microsoft Project Web Access
Working on Tasks in Microsoft Project Web AccessWorking on Tasks in Microsoft Project Web Access
Working on Tasks in Microsoft Project Web Access
 
A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...
A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...
A Deep Dive into Exploiting SaaS-Based Company Partnership Management Dashboa...
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer scriptMaker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer script
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
 
Basics of web
Basics of webBasics of web
Basics of web
 
Sending the data already gathered from the client to the Server
Sending the data already gathered from the client to the ServerSending the data already gathered from the client to the Server
Sending the data already gathered from the client to the Server
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
HDFC banking system SRS Document
HDFC banking system  SRS DocumentHDFC banking system  SRS Document
HDFC banking system SRS Document
 

Dernier

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Ajax learning tutorial

  • 1. PREFACE This tutorial is free only for educational purpose. This tutorial is not full; it helps you to just know the subject. This is good to start a beginning. We have collected study material also from out-sources which is not meant for any sales value. This tutorial is also not publishing on any commercial web site, society or any other area where it shows commercial. Shweta SofTech India erstwhile Shim SofTech India is established on 26th Jan’2006 for encouraging free I.T. education in India. We hope you will get a worth from this book. For any further query please write to us: info@shwetasoftech.com With many thanks, Shimona Arora shim@shimsoftech.com
  • 2. AJAX: ........................................................................................................................................ 1 WHAT STANDS FOR AJAX: ........................................................................................................... 2 AJAX – ENABLED WEB-PAGE: ARCHITECTURE ................................................................................ 3 AJAX – LIFE CYCLE ..................................................................................................................... 3 AJAX – WEB STANDARD .............................................................................................................. 4 WHEN DO I START USING AJAX? ..................................................................................................... 4 HOW DOES AJAX WORK? ............................................................................................................... 4 THE READYSTATE PROPERTY .........................................................................................................5 THE RESPONSETEXT PROPERTY......................................................................................................5 AJAX - SENDING A REQUEST TO THE SERVER ...............................................................................5 CROSS-BROWSER ISSUES ..................................................................................................................5 EXERCISE:..........................................................................................................................................6 AJAX: IMPLEMENTATION ......................................................................................................... 7 SIMPLE LOGIN ACTIVITY WITHOUT USE OF AJAX:..........................................................................7 APPLICATION WITH AJAX: ............................................................................................... 10 LOGIN-AJAX.HTML ......................................................................................................................... 10 CLIENTACTION-AJAX.JS................................................................................................................ 11 GETID.ASP....................................................................................................................................... 12 EXPLANATION OF AJAX APPLICATION ....................................................................................... 13 USING, AJAX, YOU CAN ALSO SOLVE ALL OTHER PROBLEMS RELATED TO DATABASES, XML ETC.EXERCISE: ............................................................................................................................... 13 EXERCISE:....................................................................................................................................... 14
  • 3. 1 AJAX-Learning Tutorial AJAX: When we started this topic many questions revolved around our minds. What is Ajax? What it does? Why we need to use it? And many more. We are here to solve all those questions. Lets starts with a simple step. First to know exactly what is it? I will tell you the full meaning of the Ajax in next lines but now let me explain that: Whenever we need some information at client side, what is happened or what did we do? In Simple words, we just send request from browser to server and get the response. Yes, this is all known as round trip. But, did you notice in this, what? Generally, when we sent a request to server from browser our entire page did get refresh and each and every page element reload the page. Or in other words lets take it in following examples: <head> <title>Login.html</title> </head> <body> <form name="myForm"> <table> <tr> <td><b>Login Id : </b> <input type="text" name="myLogin" /></td> </tr> <tr> <td><b>Password: </b> <input type="text" name="myPass" /></td> </tr> </table> <p> <input type="submit" name="myDetails" value="Login" /> </p> </form> </body> </html> The above html page looks like as: Shim SofTech India (email: info@shimsoftech.com)
  • 4. AJAX-Learning Tutorial 2 Now, what happens when user enter Login id simply nothing happens until he or she submit the request by pressing Login button. As soon as login button presses a request to server for checking the existence of the Login Id in databases or in any other source where it is located. It means whenever login button press, a request passes to the server and response gets at browser site by refreshing or reloading the entire page. Think about that page, form which contains numerous elements present on it. Isn’t it slow down the speed of the web or page on every request? Because, every time page will be reloaded its element. To redeem this issue we use AJAX. With the help of Ajax we don’t need to refresh entire page to fulfill our request. WHAT STANDS FOR AJAX: The brief terminology of the web page is cleared, also the request and response is understand. Now, let’s start with the meaning of AJAX: AJAX: ASYNCHRONOUS JAVASCRIPT AND XML To define it more deeply lets first understand the Synchronous and Asynchronous. Suppose, you want to know the existence of entered login-id (sometimes, user-id and login-id behaves synonymous but in practically user-id is the identification of the user who is permit to obtain or use the services to a particular unit or page, in the other hand Login-id ensures the entrance of a particular Login-id holder but it doesn’t mean that he or she may entitle to obtain the services. Because in some cases where security matters upto its hike, different kinds of user-id’s provided to different persons under same login-id. Suppose, you have a card to enter in office premises, you punch the card it means you logins then push back the card and enter your personal PIN or identification number with your password, all this is about Login- Id and User-ID) in a registration form. It requires when new user want to register for the services and he or she fills the registration form. At this stage what happens? Normally, request goes to server and response retrieve to browser about the existence of the entered Login Id. Our entire rest action or work is blindly depend upon this action, it means we are unable to do or process an further step until we retrieve or get the response from server. This task is known or called as Synchronous. While in the other hand the contents of entire page or some part-contents of page need the same process but out other task or work is not affect from this, is called asynchronous task(s). In general, simple and in raw words you can compare both with the two way and one-way communication. In one we have to wait the response to go ahead for next step while in other we may proceed for the further step. Shim SofTech India (email: info@shimsoftech.com)
  • 5. 3 AJAX-Learning Tutorial With the keen light of above discussion, now we are able to declare the exactly what is AJAX? AJAX is a web technology which is favorable to dynamic and rich web control/elements. It is a combination of JavaScript and XML, favoring asynchronously communication. AJAX – ENABLED WEB-PAGE: ARCHITECTURE It’s a technology and not a new to developers It is using from 2005 in Google services like Google maps and Google suggests. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. Ajax enables a new architecture. The important parts of this architecture are: 1. Small Server Side Events: Now components in a web application can make small requests back to a server, get some information, and tweak the page that is viewed by changing the DOM. No full page refresh. 2. Asynchronous: Requests posted back to the server don’t cause the browser to block. The user can continue to use other parts of the application, and the UI can be updated to alert the user that a request is taking place. 3. onAnything: We can talk back to a server based on almost anything the user does. Modern browsers trap most of the same user events that the operating system allows: mouse clicks, mouse overs, keypresses, etc. Any user event can trigger an asynchronous request. AJAX – LIFE CYCLE 1. User makes initial request against a given URL 2. Server returns original HTML page 3. Browser renders page as in-memory DOM tree 4. User activity causes subsequent request against another URL asynchronously, leaving existing DOM tree untouched 5. Browser returns data to a callback function inside the existing page 6. Browser parses result and updates in-memory DOM with the new data, which is then reflected on screen to the user (the page is redrawn, but not "refreshed") Imp: The AJAX technique makes Internet applications smaller, faster and more user-friendly. AJAX is a browser technology independent of web server software. Shim SofTech India (email: info@shimsoftech.com)
  • 6. AJAX-Learning Tutorial 4 AJAX – WEB STANDARD AJAX is based on the following web standards: • JavaScript • XML • HTML • CSS The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. WHEN DO I START USING AJAX? As already mentioned above that Ajax is very easy and based on Web Standard technology. So, if you know or have the idea of JavaScript, Xml, Html, CSS then you can start Ajax today from now. If you are unaware from the above technologies then no need to be depressed just take a beneath sitting for above topics and return back here to learn and know about the exiting and more powerful technology called AJAX. HOW DOES AJAX WORK? It’s the first question in my mind when I have started to read Ajax. As it is already discussed that this is a Technology of web based so, it also works same as other technologies work. Let’s start in simple terminology: to do start any web application we need following(s): • Platform or Form to enter user data • Server side scripting language • Client Side scripting language In previous mentioned example titled login.html provides us a form to enter information. Now for other two i.e. sever side and client side languages first, we need to understand following in more details: In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, and then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background. Shim SofTech India (email: info@shimsoftech.com)
  • 7. 5 AJAX-Learning Tutorial By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded! The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. The readyState Property The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState propery: State Description 0 The request is not initialized 1 The request has been set up 2 The request has been sent 3 The request is in process 4 The request is complete The responseText Property The data sent back from the server can be retrieved with the response Text property. This property assures the responded data of our request. AJAX - Sending a Request to the Server To send off a request to the server, we use the open() method and the send() method. The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. Cross-Browser Issues The web page painted with Ajax technology at least one rather severe cross-browser imitation. The way it initializes the XMLHttpRequest object will only function on Mozilla 1.0+ and Safari 1.2+; it does not function on Internet Explorer. On IE 5.0+, the way to create it is (discussed in following example: Shim SofTech India (email: info@shimsoftech.com)
  • 8. AJAX-Learning Tutorial 6 var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; The simple method is to obey the Try-Catch rule to initiate the same. In we have declared a variable named xmlHttp and then creating an object of XMLHttpRequest() using try-catch block. This is the universal block which is used in everywhere Ajax use. Exercise: Let’s revise 1. What is Ajax? 2. How Ajax web based Technology? 3. Write few line son Ajax Architecture defining life cycle of an Ajax web page 4. How does Ajax work? 5. How we can detect browser using try-catch bock? 6. Define four ready states of Ajax. 7. What are send() and open(0 method(s)? 8. What are cross-browsers issue? 9. What do you mean by round trip? 10. Define Login-Id and User-Id myth Shim SofTech India (email: info@shimsoftech.com)
  • 9. 7 AJAX-Learning Tutorial AJAX: IMPLEMENTATION In this head we will consider some practical exercise which favoring implementation of the Ajax: Our entire topic is depends upon the Registration and Login issues: Simple Login activity without use of Ajax: Consider our login.html example; let’s modify it with the use of JavaScript: Login.html <head> <title>Login.html</title> <script src="clientaction.js"> </Script> </head> <body onLoad="set(this.form);"> <form name="myForm"> <table> <tr> <td><b>Login Id : </b> <input type="text" name="myLogin" size="40" onBlur="checklen(this.form);" /></td> </tr> <tr> <td><b>Password: </b> <input type="text" name="myPass" size="40" /></td> </tr> </table> <p> <input type="submit" name="myDetails" value="Login" onClick="verify(this.form);" /> </p> </form> </body> </html> Shim SofTech India (email: info@shimsoftech.com)
  • 10. AJAX-Learning Tutorial 8 Clientaction.js // JavaScript Document //File Name - clientaction.js <!-- The function verify() chekd whetehr appropriate information --> <!-- filled in all the elements. I any elements is left empty, an alert() box--> <!--is displayed information the user to fill in the empty element. the code--> function verify(form) { for (i=0; i<=1;i++) { if (document.forms[0].elements[i].value=="") { alert("Please fill in the " + document.forms[0].elements[i].name +" field"); document.forms[0].elements[i].focus(); return(false); } } return(true); } <!--Sets the focus on the first element when the form loade--> function set(form) { document.forms[0].elements[0].focus() } <!--he function checklen() checks that the length of name and--> <!--email address does not exceed 30 character--> function checklen(form) { for(i=0;i<=1;i++) { val=document.forms[0].elements[i].value; len=val.length; if(len>30) { alert("Value exceeds 30 characters"); document.forms[0].elements[i].value=""; document.forms[0].elements[i].focus(); } } } Shim SofTech India (email: info@shimsoftech.com)
  • 11. 9 AJAX-Learning Tutorial With the help of above change, we can just enable client interaction but till now our problem is arisen as the same. Only some or fewer errors made at browser side will be displayed. But our main motive is asynchronous communication. The above is done when we submit the form. It means that the whole document first submit and then gets the response from the server. It will take time. Now, not wasting the time lets start our Ajax application. Shim SofTech India (email: info@shimsoftech.com)
  • 12. AJAX-Learning Tutorial 10 Application with AJAX: Login-ajax.html <head> <title>Login.html</title> <script src="clientaction-ajax.js"> </Script> </head> <body> <form name="myForm"> <table> <tr> <td><b>Login Id : </b> <input type="text" name="myLogin" size="40" onkeyup="showID(this.value)" /></td> </tr> <tr> <td><b>Password: </b> <input type="text" name="myPass" size="40" /></td> </tr> </table> <p> <font color="Blue"><b></b></font><span id="txtid"></span></p> </p> </form> </body> </html> Shim SofTech India (email: info@shimsoftech.com)
  • 13. 11 AJAX-Learning Tutorial clientaction-ajax.js var xmlHttp function showID(str) { if (str.length==0) { document.getElementById("txtid").innerHTML=""; return; } xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } var url="getid.asp"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState==4) { document.getElementById("txtid").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } Shim SofTech India (email: info@shimsoftech.com)
  • 14. AJAX-Learning Tutorial 12 getid.asp <% response.expires=-1 dim a(36) 'Fill up array with names a(1)="Anu" a(2)="Mohan" a(3)="Anil" a(4)="Sunil" a(5)="Vinita" a(6)="Subha" a(7) ="Gaurav" a(8)="Neetu" a(9)="Rachita" a(10)="Inga" a(11)="Ricky" a(12)="Rekha" a(13)="Linda" a(14)="Nina" a(15)="Ophelia" a(16)="Petunia" a(17)="Amanda" a(18)="Raquel" a(19)="Cindy" a(20)="Doris" a(21)="Eve" a(22)="Evita" a(23)="Sunniva" a(24)="Tove" a(25)="Unni" a(26)="Violet" a(26)="Liza" a(27)="Elizabeth" a(28)="Ellen" a(29)="Wenche" a(30)="Vicky" a(31)="Shimona" a(32)="Swati" a(33)="Arun" a(34)="Shikha" a(35)="Shweta" a(36)="Anu" 'get the q parameter from URL q=ucase(request.querystring("q")) 'lookup all hints from array if length of q>0 if len(q)>0 then hint="" for i=1 to 36 if q=ucase(mid(a(i),1,len(q))) then if hint="" then hint=a(i) else hint=hint & " , " & a(i) end if end if next end if if hint="" then response.write("<b>This Login Id is invalid or doesn't exist</b>") Shim SofTech India (email: info@shimsoftech.com)
  • 15. 13 AJAX-Learning Tutorial else response.write("<b>Available user(s): </b>" & hint) end if %> Explanation of Ajax Application Above example is explained as follow: 1. A Form is created, in which login id is entered 2. In the event of keyup of the field showed() function calls by passing field’s value 3. In the function we have confirmed the browser and then send the request using open() and send () method(s). 4. Get the text by checking onreadystatechange. 5. In the other hand in file getid.asp which is written in server side scripting language, we have declared an array of some id’s. 6. Now, as soon as we write in the Login Id field, available logins display in the bottom of the form and if not available then message appears. 7. This all is done using asynchronous communication. Using, Ajax, you can also solve all other problems related to databases, xml etc. Shim SofTech India (email: info@shimsoftech.com)
  • 16. AJAX-Learning Tutorial 14 Exercise: Implement ajax in following(s): 1. Create a registration form which contains Login-ID, First Name, Last Name, Password, Retype Password field(s). During the registration confirm existence of entered Login-Id. The database stores in file user.mdb 2. In continuation to above create a Login-form which permits login-id which is stored in user.xml file (the login id’s are same as stored in user.mdb file). Here using Ajax, compare the password. On successful login show the welcome window showing the Full Name and id of the user. 3. Create a text file named collection.txt which contains the information of abbreviations, like- Ajax: Asynchronous JavaScript and Xml, HTML: ypertext MarkUp Language, ASP: Active Server Pages, PHP: PHP Hypertext Preprocessor etc. Create a form where user enter any words then retrieve the information related to that word (if exists), if information of entered word is not found in the collection ask user to enter the proper definition of that words by showing Id and definition field(s). remember ID and definition field are like AJAX (ID) and Asynchronous JavaScript and Xml (definition). 4. Recreate above application using database(s) instead of text file(s). To obtain the full collection of codes please write to us: infor@shwetasoftech.com under subject: Ajax-examples. These all are free and anyone can use these examples as these ae meant for only educational purpose. Shim SofTech India (email: info@shimsoftech.com)