SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
AJAX Tutorial

Introduction

This tutorial assumes that you have the basic knowledge of HTML, JavaScript and the basis of the client-server
model. That is all you need to start building basic AJAX applications.

What is AJAX?

Just for your information, AJAX stands for Asynchronous JavaScript And XML. But don’t pay much attention to the
name; it is unfortunately chosen. What you need to know is that AJAX is not a new technology, it is a combination
of existing technologies like HTML, JavaScript, DHTML and DOM. Really it’s just an innovative approach to
combine these technologies to suit the needs of the always developing web applications.

What can AJAX do for you?

AJAX can make your webapps more user friendly. Perhaps the easiest illustration is when a user is filling some king
of form as a part of your webapp and based on the partial user input you can perform a database check
transparently to the user while he is still busy with filling the rest of the form. As a result of that asynchronous
request you can assist the user with various information(like username is taken, auto fill the rest of the form…)
making the GUI of the webapp user-friendly like the one of a standard stand-alone application.

Mixing the Technologies

Here are the basic technologies involved in AJAX:

      HTML is used to build web forms and identify fields that you’ll use in the rest of the webapp
      JavaScript code is the code used in AJAX to facilitate communication with server applications
      DHTML, of Dynamic HTML, helps you update your forms dynamically through usage of div, span and other
       dynamic HTML elements
      DOM, the Document Object Model, is used to work with both the structure of your HTML and (in some cases)
       the XML returned from the server.

The XMLHttpRequest object

In this second part of this tutorial we'll take a look at the XMLHttpRequest object; object that you'll need in order to
make asynchronous requests to the server logic. It's quite simple and most of the time you'll either retype the creation
and request code of use ctrl-C/V. So, let's get started.

What is XMLHttpRequest object?

Basically, it is a JavaScript object, nothing more. Here's the code you need to create it:

Listing 1. Create a new XMLHttpRequest object
 <script language="javascript" type="text/javascript">
         var xmlHttp = new XMLHttpRequest();
 </script>


What it should be clear to you about this object is that this is the object that does the communication with the server
logic using JavaScript technology, nothing more. So, what AJAX basically does is that it puts this object between
your webapplication user forms and the webserver logic(some script, like cgi, php, jsp/servlet..). This is the new
thinking that lets the web application to have the user interface friendliness like a desktop application, but with all the
power of the Internet behind it.

Dealing with Multiple Browsers
Unfortunatelly, the proper creation of the XMLHttpRequest object is not so simple thanks to the variety of browsers.
For example, the above code will work with Microsoft browsers. Without getting further in the problems, I'll simply
present a code that you can use that will create the XMLHttpRequest object no matter the browser and report an error
message if the client has JavaScript disabled in her/his browser. Here's that code:

Listing 2. Dealing with various browsers
 var xmlHttp = false;
 /*@cc_on @*/
 /*@if (@_jscript_version >= 5)
 try {
          /* try the first version of JavaScript in IE */
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
          /* try the second version of JavaScript in IE */
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e2) {
     xmlHttp = false;
   }
 }
 @end @*/
 /* else create the object the non-Microsoft way */
 if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
   xmlHttp = new XMLHttpRequest();
 }



Don't mind the fancy compiler-spicific tags like @cc_on, just remember that this is the code that you can rely on to
sucesfully create the XMLHttpRequest no matter the browser.

Adding some standard JavaScript

We know how to create the XMLHttpRequest object that we need in order to communicate with the server logic
(invoke a particular script). Now we need to learn how to put information in this object in order to pass information
to the web server that the script needs in order to satisfy the request. Next, we need to make the request and receive
the response that we can use to update the form that the user is woking on. Suppose the following scenario:

The user of our web application is using a form to modify the information regarding a warehouse item already stored
in the database. In most cases, the user will want to change a field or two about the item(eg. new address and website)
but wants to view all the current information about the item. Instead of requiring the user to rewrite ALL the
information about the item, we can use AJAX to detect the selection of the itemID from an drop-down menu and use
that info to fetch the appropriate related data for the item from the database. This means that the user in a second or
two will have all the information for the item auto-filled in the form and can only modify the ones it needs. That's the
user-friendliness I was talking about earlier. The code to do such a thing is not complicated. In the following sections
I'll present and explain the parts needed for that code and in the final section we'll reassemble that whole code. So let's
get started!

1. Preparing our user form

First, we need to slightly modify our user form in order for it's elements to be accessible through our code. Again, this
is not something new it's just regular HTML. This typically means adding id attributes to our form elements in order
to identify those elements and using the onChange attribute to specify the action that should be taken when its value
changes( the user types something on it or selects it from drop-down menu ). To simplify our code we consider that
the user types the itemID in a input field. The exactly same attributes(id and onChange) can be added to drop-down
menus or whatever form element. Here's the code:

Listing 3. Preraring out input form for some AJAX usage
<form...>
 <input type="text" name="itemID" id="item"
                         onChange="callServer();">
 (...may add other elements here using usual HTML...)
 </form...>
 <div id="newForm">
         On this place a whole pre-filled form
         will appear according to the selection of
         the itemID field. This form will the created
         by the server.
 </div>



There are two things to remember(in case you never used them in your HTML's): the id attribute whose value we'll
use in our AJAX(well the JavaScript part of AJAX) code to retrieve the values from the form elements and to
dispatch those values to the server logic, using XMLHttpRequest ofcourse.
The second onChange attribute is used to indicate which JavaScript method to invoke in order to process the event
that has occured, that is, the user typed something in the field. That method, in this case, is named callServer, but can
be any other name.

2. Creating the XMLHttpRequest, dispatching the request and handling the response

In this step, we create the XMLHttpRequest object, that is the object that is responsible for handling the
communication between the client and the server, we retrieve the user-entered itemID from the form, issue a request
to the server with the retrieved parameter as argument to that request and handling the server response. The creation
of the XMLHttpRequest object is exactly the same as above, and the same code is used here. Now look at the code
and afterwards we'll see and explain the new things:

Listing 4. Creating XMLHttpRequest and issuing the request
 /* Creating the XMLHttpRequest same as above */
 var xmlHttp = false;
 /*@cc_on @*/
 /*@if (@_jscript_version >= 5)
 try {
          /* try the first version of JavaScript in IE */
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
          /* try the second version of JavaScript in IE */
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e2) {
     xmlHttp = false;
   }
 }
 @end @*/
 /* else create the object the non-Microsoft way */
 if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
   xmlHttp = new XMLHttpRequest();
 }

 /* the 'new' part:*/

 /* 1. retrieving the entered data and
 issuing the request */
 function callServer() {
         //Get the itemID value from the form elements
         var item = document.getElementById("item");

           //check whether the element has value
           if((item==null) || (item=="")) return;
//make the URL that will process the request
           var url = "/scripts/getItemInformation?item="
                           +escape(item);

           //make a connection to the server
           xmlHttp = OPEN("GET",url,true);

           // Setup a function for the server to run when it's done
           xmlHttp.onreadystatechange = updatePage;

           // Send the request
           xmlHttp.send(null);
 }

 /* 2. handling the server response */
 function updatePage() {
         if (xmlHttp.readyState == 4) {
     var response = xmlHttp.responseText;
     document.getElementById("newForm").value = response;
   }
 }




Now, let's clear things up. In the first part we create the XMLHttpRequest object as usual. Afterwards, we dispatch
the request to the server. The substeps used are to retrieve the value using getElementById(that's why we specified
the id attribute previously when we were preparing our form for AJAX/JavaScript usage. Afterwards, we checked
whether the value retrieved is valid and build the URL to the server script that will process the request passing the
retrieved data as it's parameter. Then, we opened the connection to the server declaring that we're going to use a GET
request(in a future tutorials i'll cover the POST request), the URL we've just build and a boolean literal of true(don't
worry about the meaning, just know it's should be true). Next, we declare which function should be invoked when the
server finishes the processing of our request which is updatePage in our case. In the last step, we effect the things
that we declared in the previous steps by issuing a send(null) call to the XMLHttpRequest object we created
previously.
What's left is to implement the updatePage function that will handle the response and make the changes to the user
form. In the first line we check whether it is safe to use the response(checking whether the server has finished with
the generation of the response for sure). Don't worry about its meaning, just know that when readyState has a value
of 4 you're safe with using the response, no matter the browser. In the last line, we just display the result from the
server to our form. In our case, the response is a newly generated form that has it's fields preset to the appropriate
values specific to the selected itemID field by the user. We're just taking that whole prepared response and we're
putting it in display in our form.
As a result of this, our user just after selecting the itemID will get a brand new preset form on it's page, asking it to
just modify the fields he feels need changes. That's the user-friendliness of the webapp GUI that was not possible
with the standard way of thinking about the client/server requests.

An end note

The abobe illustrative example is just one example of the AJAX approach. Use your creativity and think of the
possible applications that AJAX can have in order for you to make rich, responsive web applications. We have to
admit that no matter how efficient, clever and innovative your underlying application logic is, without the ease of use
and the impressive GUI, in the eyes of the user your application will be dull and repulsive!

This isn't goodbye!

I hope I helped you to learn the basis of the AJAX approach and I sincerely hope that in the past hours you've actually
lerned something from this tutorial. If so, please drop me a note at ipenov@gmail.com and tell me how can I
improve it. In the meantime, visit this page for some more tutorials and software.
Thanks, Ice

Mais conteúdo relacionado

Mais procurados

Mais procurados (19)

JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Copy of ajax tutorial
Copy of ajax tutorialCopy of ajax tutorial
Copy of ajax tutorial
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
JavaScript Libraries
JavaScript LibrariesJavaScript Libraries
JavaScript Libraries
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
Ajax
AjaxAjax
Ajax
 
Java scripts
Java scriptsJava scripts
Java scripts
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Ajax
AjaxAjax
Ajax
 

Destaque

Solidoscristalinos telsup
Solidoscristalinos telsupSolidoscristalinos telsup
Solidoscristalinos telsupVanz Leggoras
 
Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...
Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...
Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...Haidee Thomson
 
MacPort japanese_ver.1.0
MacPort japanese_ver.1.0MacPort japanese_ver.1.0
MacPort japanese_ver.1.0Satoshi Kume
 
Igor_pro_ODE_japanese_ver2.0
Igor_pro_ODE_japanese_ver2.0 Igor_pro_ODE_japanese_ver2.0
Igor_pro_ODE_japanese_ver2.0 Satoshi Kume
 
Regime shfits montpellier
Regime shfits montpellierRegime shfits montpellier
Regime shfits montpellierJuan C. Rocha
 
Wildlife Hazards, the FAA and the Inspector General's Audit Report
Wildlife Hazards, the FAA and the Inspector General's Audit ReportWildlife Hazards, the FAA and the Inspector General's Audit Report
Wildlife Hazards, the FAA and the Inspector General's Audit ReportSteven Taber
 

Destaque (8)

Solidoscristalinos telsup
Solidoscristalinos telsupSolidoscristalinos telsup
Solidoscristalinos telsup
 
Branding seminar 30 march2012
Branding seminar 30 march2012Branding seminar 30 march2012
Branding seminar 30 march2012
 
Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...
Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...
Exploring attitudes towards peer feedback in the writing classroom ライティングにおける...
 
MacPort japanese_ver.1.0
MacPort japanese_ver.1.0MacPort japanese_ver.1.0
MacPort japanese_ver.1.0
 
Web Hosting
Web HostingWeb Hosting
Web Hosting
 
Igor_pro_ODE_japanese_ver2.0
Igor_pro_ODE_japanese_ver2.0 Igor_pro_ODE_japanese_ver2.0
Igor_pro_ODE_japanese_ver2.0
 
Regime shfits montpellier
Regime shfits montpellierRegime shfits montpellier
Regime shfits montpellier
 
Wildlife Hazards, the FAA and the Inspector General's Audit Report
Wildlife Hazards, the FAA and the Inspector General's Audit ReportWildlife Hazards, the FAA and the Inspector General's Audit Report
Wildlife Hazards, the FAA and the Inspector General's Audit Report
 

Semelhante a ajax_pdf (20)

Ajax
AjaxAjax
Ajax
 
AJAX
AJAXAJAX
AJAX
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax
AjaxAjax
Ajax
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Ajax
AjaxAjax
Ajax
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
AJAX Workshop Notes
AJAX Workshop NotesAJAX Workshop Notes
AJAX Workshop Notes
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
M Ramya
M RamyaM Ramya
M Ramya
 
25250716 seminar-on-ajax text
25250716 seminar-on-ajax text25250716 seminar-on-ajax text
25250716 seminar-on-ajax text
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
Ajax
AjaxAjax
Ajax
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
AJAX
AJAXAJAX
AJAX
 

Mais de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

Mais de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Último

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Último (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

ajax_pdf

  • 1. AJAX Tutorial Introduction This tutorial assumes that you have the basic knowledge of HTML, JavaScript and the basis of the client-server model. That is all you need to start building basic AJAX applications. What is AJAX? Just for your information, AJAX stands for Asynchronous JavaScript And XML. But don’t pay much attention to the name; it is unfortunately chosen. What you need to know is that AJAX is not a new technology, it is a combination of existing technologies like HTML, JavaScript, DHTML and DOM. Really it’s just an innovative approach to combine these technologies to suit the needs of the always developing web applications. What can AJAX do for you? AJAX can make your webapps more user friendly. Perhaps the easiest illustration is when a user is filling some king of form as a part of your webapp and based on the partial user input you can perform a database check transparently to the user while he is still busy with filling the rest of the form. As a result of that asynchronous request you can assist the user with various information(like username is taken, auto fill the rest of the form…) making the GUI of the webapp user-friendly like the one of a standard stand-alone application. Mixing the Technologies Here are the basic technologies involved in AJAX:  HTML is used to build web forms and identify fields that you’ll use in the rest of the webapp  JavaScript code is the code used in AJAX to facilitate communication with server applications  DHTML, of Dynamic HTML, helps you update your forms dynamically through usage of div, span and other dynamic HTML elements  DOM, the Document Object Model, is used to work with both the structure of your HTML and (in some cases) the XML returned from the server. The XMLHttpRequest object In this second part of this tutorial we'll take a look at the XMLHttpRequest object; object that you'll need in order to make asynchronous requests to the server logic. It's quite simple and most of the time you'll either retype the creation and request code of use ctrl-C/V. So, let's get started. What is XMLHttpRequest object? Basically, it is a JavaScript object, nothing more. Here's the code you need to create it: Listing 1. Create a new XMLHttpRequest object <script language="javascript" type="text/javascript"> var xmlHttp = new XMLHttpRequest(); </script> What it should be clear to you about this object is that this is the object that does the communication with the server logic using JavaScript technology, nothing more. So, what AJAX basically does is that it puts this object between your webapplication user forms and the webserver logic(some script, like cgi, php, jsp/servlet..). This is the new thinking that lets the web application to have the user interface friendliness like a desktop application, but with all the power of the Internet behind it. Dealing with Multiple Browsers
  • 2. Unfortunatelly, the proper creation of the XMLHttpRequest object is not so simple thanks to the variety of browsers. For example, the above code will work with Microsoft browsers. Without getting further in the problems, I'll simply present a code that you can use that will create the XMLHttpRequest object no matter the browser and report an error message if the client has JavaScript disabled in her/his browser. Here's that code: Listing 2. Dealing with various browsers var xmlHttp = false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { /* try the first version of JavaScript in IE */ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { /* try the second version of JavaScript in IE */ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } } @end @*/ /* else create the object the non-Microsoft way */ if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } Don't mind the fancy compiler-spicific tags like @cc_on, just remember that this is the code that you can rely on to sucesfully create the XMLHttpRequest no matter the browser. Adding some standard JavaScript We know how to create the XMLHttpRequest object that we need in order to communicate with the server logic (invoke a particular script). Now we need to learn how to put information in this object in order to pass information to the web server that the script needs in order to satisfy the request. Next, we need to make the request and receive the response that we can use to update the form that the user is woking on. Suppose the following scenario: The user of our web application is using a form to modify the information regarding a warehouse item already stored in the database. In most cases, the user will want to change a field or two about the item(eg. new address and website) but wants to view all the current information about the item. Instead of requiring the user to rewrite ALL the information about the item, we can use AJAX to detect the selection of the itemID from an drop-down menu and use that info to fetch the appropriate related data for the item from the database. This means that the user in a second or two will have all the information for the item auto-filled in the form and can only modify the ones it needs. That's the user-friendliness I was talking about earlier. The code to do such a thing is not complicated. In the following sections I'll present and explain the parts needed for that code and in the final section we'll reassemble that whole code. So let's get started! 1. Preparing our user form First, we need to slightly modify our user form in order for it's elements to be accessible through our code. Again, this is not something new it's just regular HTML. This typically means adding id attributes to our form elements in order to identify those elements and using the onChange attribute to specify the action that should be taken when its value changes( the user types something on it or selects it from drop-down menu ). To simplify our code we consider that the user types the itemID in a input field. The exactly same attributes(id and onChange) can be added to drop-down menus or whatever form element. Here's the code: Listing 3. Preraring out input form for some AJAX usage
  • 3. <form...> <input type="text" name="itemID" id="item" onChange="callServer();"> (...may add other elements here using usual HTML...) </form...> <div id="newForm"> On this place a whole pre-filled form will appear according to the selection of the itemID field. This form will the created by the server. </div> There are two things to remember(in case you never used them in your HTML's): the id attribute whose value we'll use in our AJAX(well the JavaScript part of AJAX) code to retrieve the values from the form elements and to dispatch those values to the server logic, using XMLHttpRequest ofcourse. The second onChange attribute is used to indicate which JavaScript method to invoke in order to process the event that has occured, that is, the user typed something in the field. That method, in this case, is named callServer, but can be any other name. 2. Creating the XMLHttpRequest, dispatching the request and handling the response In this step, we create the XMLHttpRequest object, that is the object that is responsible for handling the communication between the client and the server, we retrieve the user-entered itemID from the form, issue a request to the server with the retrieved parameter as argument to that request and handling the server response. The creation of the XMLHttpRequest object is exactly the same as above, and the same code is used here. Now look at the code and afterwards we'll see and explain the new things: Listing 4. Creating XMLHttpRequest and issuing the request /* Creating the XMLHttpRequest same as above */ var xmlHttp = false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { /* try the first version of JavaScript in IE */ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { /* try the second version of JavaScript in IE */ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } } @end @*/ /* else create the object the non-Microsoft way */ if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } /* the 'new' part:*/ /* 1. retrieving the entered data and issuing the request */ function callServer() { //Get the itemID value from the form elements var item = document.getElementById("item"); //check whether the element has value if((item==null) || (item=="")) return;
  • 4. //make the URL that will process the request var url = "/scripts/getItemInformation?item=" +escape(item); //make a connection to the server xmlHttp = OPEN("GET",url,true); // Setup a function for the server to run when it's done xmlHttp.onreadystatechange = updatePage; // Send the request xmlHttp.send(null); } /* 2. handling the server response */ function updatePage() { if (xmlHttp.readyState == 4) { var response = xmlHttp.responseText; document.getElementById("newForm").value = response; } } Now, let's clear things up. In the first part we create the XMLHttpRequest object as usual. Afterwards, we dispatch the request to the server. The substeps used are to retrieve the value using getElementById(that's why we specified the id attribute previously when we were preparing our form for AJAX/JavaScript usage. Afterwards, we checked whether the value retrieved is valid and build the URL to the server script that will process the request passing the retrieved data as it's parameter. Then, we opened the connection to the server declaring that we're going to use a GET request(in a future tutorials i'll cover the POST request), the URL we've just build and a boolean literal of true(don't worry about the meaning, just know it's should be true). Next, we declare which function should be invoked when the server finishes the processing of our request which is updatePage in our case. In the last step, we effect the things that we declared in the previous steps by issuing a send(null) call to the XMLHttpRequest object we created previously. What's left is to implement the updatePage function that will handle the response and make the changes to the user form. In the first line we check whether it is safe to use the response(checking whether the server has finished with the generation of the response for sure). Don't worry about its meaning, just know that when readyState has a value of 4 you're safe with using the response, no matter the browser. In the last line, we just display the result from the server to our form. In our case, the response is a newly generated form that has it's fields preset to the appropriate values specific to the selected itemID field by the user. We're just taking that whole prepared response and we're putting it in display in our form. As a result of this, our user just after selecting the itemID will get a brand new preset form on it's page, asking it to just modify the fields he feels need changes. That's the user-friendliness of the webapp GUI that was not possible with the standard way of thinking about the client/server requests. An end note The abobe illustrative example is just one example of the AJAX approach. Use your creativity and think of the possible applications that AJAX can have in order for you to make rich, responsive web applications. We have to admit that no matter how efficient, clever and innovative your underlying application logic is, without the ease of use and the impressive GUI, in the eyes of the user your application will be dull and repulsive! This isn't goodbye! I hope I helped you to learn the basis of the AJAX approach and I sincerely hope that in the past hours you've actually lerned something from this tutorial. If so, please drop me a note at ipenov@gmail.com and tell me how can I improve it. In the meantime, visit this page for some more tutorials and software.