Ajax learning tutorial

5,415
-1

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
5,415
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
50
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ajax learning tutorial

  1. 1. PREFACEThis tutorial is free only for educational purpose. This tutorial is not full; it helps you to justknow the subject. This is good to start a beginning.We have collected study material also from out-sources which is not meant for any salesvalue. This tutorial is also not publishing on any commercial web site, society or any otherarea where it shows commercial.Shweta SofTech India erstwhile Shim SofTech India is established on 26th Jan’2006 forencouraging 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.comWith many thanks,Shimona Arorashim@shimsoftech.com
  2. 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:..........................................................................................................................................6AJAX: 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. 3. 1 AJAX-Learning TutorialAJAX:When we started this topic many questions revolved around our minds. What is Ajax? What itdoes? 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 exactlywhat is it? I will tell you the full meaning of the Ajax in next lines but now let me explainthat:Whenever we need some information at client side, what is happened or what did we do? InSimple words, we just send request from browser to server and get the response. Yes, this isall 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 andeach and every page element reload the page. Or in other words lets take it in followingexamples:<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. 4. AJAX-Learning Tutorial 2Now, what happens when user enter Login id simply nothing happens until he or she submitthe request by pressing Login button. As soon as login button presses a request to server forchecking 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 atbrowser site by refreshing or reloading the entire page.Think about that page, form which contains numerous elements present on it. Isn’t it slowdown the speed of the web or page on every request? Because, every time page will bereloaded its element.To redeem this issue we use AJAX. With the help of Ajax we don’t need to refresh entirepage 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 XMLTo 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 andlogin-id behaves synonymous but in practically user-id is theidentification of the user who is permit to obtain or use theservices to a particular unit or page, in the other hand Login-idensures the entrance of a particular Login-id holder but it doesn’tmean that he or she may entitle to obtain the services. Because insome cases where security matters upto its hike, different kinds ofuser-id’s provided to different persons under same login-id. Suppose,you have a card to enter in office premises, you punch the card itmeans you logins then push back the card and enter your personal PINor 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 theservices 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 enteredLogin Id. Our entire rest action or work is blindly depend upon this action, it means we areunable to do or process an further step until we retrieve or get the response from server. Thistask is known or called as Synchronous. While in the other hand the contents of entire page orsome part-contents of page need the same process but out other task or work is not affect fromthis, is called asynchronous task(s).In general, simple and in raw words you can compare both with the two way and one-waycommunication. In one we have to wait the response to go ahead for next step while in otherwe may proceed for the further step.Shim SofTech India (email: info@shimsoftech.com)
  5. 5. 3 AJAX-Learning TutorialWith the keen light of above discussion, now we are able to declare the exactly what isAJAX?AJAX is a web technology which is favorable to dynamic and rich web control/elements. It isa combination of JavaScript and XML, favoring asynchronously communication.AJAX – ENABLED WEB-PAGE: ARCHITECTUREIt’s a technology and not a new to developers It is using from 2005 in Google services likeGoogle maps and Google suggests.With AJAX, your JavaScript can communicate directly with the server, using the JavaScriptXMLHttpRequest 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 webserver, allowing web pages to request small bits of information from the server instead ofwhole 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 independentof web server software. Shim SofTech India (email: info@shimsoftech.com)
  6. 6. AJAX-Learning Tutorial 4AJAX – WEB STANDARDAJAX is based on the following web standards: • JavaScript • XML • HTML • CSSThe 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 todayfrom now.If you are unaware from the above technologies then no need to be depressed just take abeneath sitting for above topics and return back here to learn and know about the exiting andmore 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 discussedthat 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 languageIn 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 understandfollowing in more details:In traditional JavaScript coding, if you want to get any information from a database or a fileon the server, or send user information to a server, you will have to make an HTML form andGET or POST data to the server. The user will have to click the "Submit" button to send/getthe 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 webapplications can run slowly and tend to be less user-friendly.With AJAX, your JavaScript communicates directly with the server, through the JavaScriptXMLHttpRequest object With an HTTP request, a web page can make a request to, and get aresponse 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 thebackground.Shim SofTech India (email: info@shimsoftech.com)
  7. 7. 5 AJAX-Learning TutorialBy using the XMLHttpRequest object, a web developer can update a page with data from theserver 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 PropertyThe readyState property holds the status of the servers response. Each time the readyStatechanges, the onreadystatechange function will be executed. Here are the possible values forthe 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 completeThe responseText PropertyThe data sent back from the server can be retrieved with the response Text property. Thisproperty assures the responded data of our request.AJAX - Sending a Request to the ServerTo 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 usewhen sending the request (GET or POST). The second argument specifies the URL of theserver-side script. The third argument specifies that the request should be handledasynchronously.The send() method sends the request off to the server.Cross-Browser IssuesThe web page painted with Ajax technology at least one rather severe cross-browserimitation. The way it initializes the XMLHttpRequest object will only function on Mozilla1.0+ and Safari 1.2+; it does not function on Internet Explorer. On IE 5.0+, the way to createit is (discussed in following example: Shim SofTech India (email: info@shimsoftech.com)
  8. 8. AJAX-Learning Tutorial 6var xmlHttp=null;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}catch (e){// Internet Explorertry{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 avariable named xmlHttp and then creating an object of XMLHttpRequest() using try-catchblock. 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 mythShim SofTech India (email: info@shimsoftech.com)
  9. 9. 7 AJAX-Learning TutorialAJAX: IMPLEMENTATIONIn this head we will consider some practical exercise which favoring implementation of theAjax: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. 10. AJAX-Learning Tutorial 8Clientaction.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, analert() 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. 11. 9 AJAX-Learning TutorialWith the help of above change, we can just enable client interaction but till now our problemis arisen as the same.Only some or fewer errors made at browser side will be displayed. But our main motive isasynchronous communication. The above is done when we submit the form. It means that thewhole 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. 12. AJAX-Learning Tutorial 10Application 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><spanid="txtid"></span></p> </p></form></body></html>Shim SofTech India (email: info@shimsoftech.com)
  13. 13. 11 AJAX-Learning Tutorialclientaction-ajax.jsvar xmlHttpfunction 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+, SafarixmlHttp=new XMLHttpRequest();}catch (e){// Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}}return xmlHttp;} Shim SofTech India (email: info@shimsoftech.com)
  14. 14. AJAX-Learning Tutorial 12getid.asp<%response.expires=-1dim a(36)Fill up array with namesa(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 URLq=ucase(request.querystring("q"))lookup all hints from array if length of q>0if len(q)>0 thenhint=""for i=1 to 36if q=ucase(mid(a(i),1,len(q))) thenif hint="" thenhint=a(i)elsehint=hint & " , " & a(i)end ifend ifnextend ifif hint="" thenresponse.write("<b>This Login Id is invalid or doesnt exist</b>")Shim SofTech India (email: info@shimsoftech.com)
  15. 15. 13 AJAX-Learning Tutorialelseresponse.write("<b>Available user(s): </b>" & hint)end if%>Explanation of Ajax ApplicationAbove 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. 16. AJAX-Learning Tutorial 14Exercise: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 undersubject: Ajax-examples. These all are free and anyone can use these examples as these aemeant for only educational purpose.Shim SofTech India (email: info@shimsoftech.com)

×