SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Building
Applications
using AJAX

WebOSS ‘07
S Pradeep
What is AJAX?
 AJAX = Asynchronous JavaScript And XML
 Is a web development technique used for
 creating faster, interactive web applications.
Who uses AJAX?
 Google maps
 Gmail
 Google Suggest
 Flickr
 del.icio.us
 Meebo
 and many more…
How AJAX is different
Need for AJAX
 To increase web's interactivity, speed and
 usability
 Issues with classic web applications
 * Almost all processing is done on server
 * High latency
 * Low interactivity
Benefits of Using AJAX
 Enhance your sites by allowing quicker
 access to data.
 Reduce the amount of bandwidth used in
 data presentation.
 Make a web application that feels more like
 a native application.
AJAX Workarounds
 Hidden IFRAME
 <SCRIPT> src hack
 Cookies
Where to use AJAX
 Anywhere you have a search box, adding
 Google suggest functionality.
 Pages where you have a multi-step process.
 When working with large or highly
 interdependent datasets.
Simple Ajax Application : How To
 Create a request object
 Make the request
 Handle the response
Create a request object
if browser is mozilla or safari or opera then
   create a new XMLHttpRequest
otherwise if browser is IE
   create a new ActiveXObject
otherwise
   error - browser does not support XMLHttpRequest


  IE 5,5.5,6 implement XHR as an ActiveX
  object
  (Msxml2.XMLHTTP/Microsoft.XMLHTTP)
  Mozilla 1.0+, Safari 1.2+, Opera 8+, IE7
  provide XMLHttpRequest natively.
  All XHR objects have the same methods and
  properties.
Code
var xhr = null;
if(window.XMLHttpRequest) // Mozilla,Safari, etc.
{
  xhr = new XMLHttpRequest();
}
else if(window.ActiveXObject) // < IE 7
{
  xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
Else
{
  alert('Oops! Your browser does not support
  XMLHttpRequest');
}
XHR Methods
 open(‘method’,’url’,asyncFlag)
 send(content)
 abort()
 getResponseHeader(“header”)
 setRequestHeader(“header”,”value”)
XHR properties
 onreadystatechange
 readystate
 responseText
 responseXML
 status
 statusText
Make the request
 set onreadystatechange to callback function
 cbProcessResponse
 open a request on the XHR object
 send the request through the XHR object
 “Same Site” rule
 “GET” or “POST”
 Asynchronous flag
Code
xhr.onreadystatechange=cbProcessResponse;
xhr.open(’GET’,‘ajax.php’,true);

function cbProcessResponse()
{
   if(xhr.readystate==4 && xhr.status==200)
   {
       alert(xhr.responseText);
   }
}

/* readystate values
0 -> uninitialized
1 -> loading
2 -> loaded
3 -> interactive
4 -> completed
*/
Handle Response: Parsing the XML
// Our sample XML
<?xml version=quot;1.0quot; encoding=quot;ISO-8859-1quot;?>
<root>
   <response>OK</response>
   <msg>Hello World!</msg>
</root>

// Revised callback function
function cbProcessResponse()
{
   if(xhr.readystate==4 && xhr.status==200)
   {
     var xmlDoc = xhr.responseXML.documentElement;
     var s = x.getElementsByTagName('response')[0].firstChild.data;
     var m = x.getElementsByTagName('msg')[0].firstChild.data;
     alert(‘Response Code:’+s+’nMessage: ‘+m)
   }
}
Enter JSON
  JavaScript Object Notation
  JSON is a lightweight data-interchange format.
  JSON data are slightly simpler and slightly more in
  line with the rest of the JavaScript language than
  scripts for XML data.
  Find more about JSON at http://json.org

//sample JSON
{
   response: ‘OK’,
   msg: ‘Hello World’
}
JSON How?
  JSON can be generated by all the popular server-side languages.
  Native/Library Support

// Revised callback function to use JSON
function cbProcessResponse()
{
  if(xhr.readystate==4 && xhr.status==200)
  {
    var jsonData = eval(‘(‘+xhr.responseText+’)’);
    var s = jsonData.response; // easy ;-)
    var m = jsonData.msg;
    alert(‘Response Code:’+s+’nMessage: ‘+m)
  }
}

  Doesn’t that look simpler?
Frameworks
 A framework is a re-usable design for a
 software system with built-in generic
 functions for performing repetitive, natively
 unsupported operations.
 The Prototype JavaScript Framework is
 a JavaScript framework that provides an
 Ajax framework and other utilities.
 Download from http://prototypejs.org
 Others: YUI, Dojo, jQuery, mooTools
Using Prototype.js
  Prototype provides the Ajax object to abstract the
  different browsers.
  Ajax.Request()
  Ajax.Updater(container, url[, options])
var pars = 'topic=ajax&framework=pjs';
Var url = '/cgi-bin/myAjaxHandler.cgi';
var myAjax = new Ajax.Request(url,{
        method: quot;postquot;, // get/post
        parameters: pars,
        onComplete: cbProcessResponse // Our old callback
   function
        });


  Ajax.PeriodicalUpdater(container, url[, options])
Tips
 Don't overuse AJAX, the usability
 requirements for JavaScript applications are
 quite different than the requirements for
 regular web pages.
 Escape content sent to the server.
 Use AJAX activity indicators.
 http://www.napyfab.com/ajax-indicators/
Debugging AJAX
 Always test your PHP/Server-side code
 before integrating it with the JavaScript
 side.
 Always check xhr.status
 Use FireBug to pin-point errors, and trace
 performance bottle-necks.
 Download from http://www.getfirebug.com/
Resources
 AJAXIAN - http://ajaxian.com
 AJAX info - http://ajaxinfo.com
 AJAX Lesson - http://ajaxlessons.com
 Go4Expert - http://go4expert.com
Thanks!
 Hussain Fakhruddin
 Teknowledge Software




 The wonderful audience.

Contenu connexe

Tendances

Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 

Tendances (20)

Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple Steps
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
CakePHP REST Plugin
CakePHP REST PluginCakePHP REST Plugin
CakePHP REST Plugin
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Node js crash course session 3
Node js crash course   session 3Node js crash course   session 3
Node js crash course session 3
 
Develop webservice in PHP
Develop webservice in PHPDevelop webservice in PHP
Develop webservice in PHP
 
JSON REST API for WordPress
JSON REST API for WordPressJSON REST API for WordPress
JSON REST API for WordPress
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
React with WordPress : Headless CMS
React with WordPress : Headless CMSReact with WordPress : Headless CMS
React with WordPress : Headless CMS
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
The Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReSTThe Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReST
 
Node js crash course session 2
Node js crash course   session 2Node js crash course   session 2
Node js crash course session 2
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect Partners
 
Build Modern Web Applications with React and WordPress
Build Modern Web Applications with React and WordPressBuild Modern Web Applications with React and WordPress
Build Modern Web Applications with React and WordPress
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 

En vedette

Ajax Introduction Presentation
Ajax   Introduction   PresentationAjax   Introduction   Presentation
Ajax Introduction Presentation
thinkphp
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
hchen1
 
Intro to SPA using JavaScript & ASP.NET
Intro to SPA using JavaScript & ASP.NETIntro to SPA using JavaScript & ASP.NET
Intro to SPA using JavaScript & ASP.NET
Alan Hecht
 

En vedette (18)

Jsf Ajax
Jsf AjaxJsf Ajax
Jsf Ajax
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Ajax Introduction Presentation
Ajax   Introduction   PresentationAjax   Introduction   Presentation
Ajax Introduction Presentation
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Intro to SPA using JavaScript & ASP.NET
Intro to SPA using JavaScript & ASP.NETIntro to SPA using JavaScript & ASP.NET
Intro to SPA using JavaScript & ASP.NET
 
WebApp / SPA @ AllFacebook Developer Conference
WebApp / SPA @ AllFacebook Developer ConferenceWebApp / SPA @ AllFacebook Developer Conference
WebApp / SPA @ AllFacebook Developer Conference
 
Writing SPA in 2017
Writing SPA in 2017Writing SPA in 2017
Writing SPA in 2017
 
Webinar on Angular JS titled 'Develop Responsive Single Page Application'
Webinar on Angular JS titled 'Develop Responsive Single Page Application'Webinar on Angular JS titled 'Develop Responsive Single Page Application'
Webinar on Angular JS titled 'Develop Responsive Single Page Application'
 
Single page application
Single page applicationSingle page application
Single page application
 
Single page application
Single page applicationSingle page application
Single page application
 
Single Page Application presentation
Single Page Application presentationSingle Page Application presentation
Single Page Application presentation
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
SPA 2009 - Acceptance Testing AJAX Web Applications through the GUI
SPA 2009 - Acceptance Testing AJAX Web Applications through the GUISPA 2009 - Acceptance Testing AJAX Web Applications through the GUI
SPA 2009 - Acceptance Testing AJAX Web Applications through the GUI
 

Similaire à Building Applications Using Ajax

Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
Kat Roque
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
dominion
 

Similaire à Building Applications Using Ajax (20)

mukesh
mukeshmukesh
mukesh
 
Ajax
AjaxAjax
Ajax
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
 
Ajax3
Ajax3Ajax3
Ajax3
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Pracitcal AJAX
Pracitcal AJAXPracitcal AJAX
Pracitcal AJAX
 
Ajax
AjaxAjax
Ajax
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Beyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsBeyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 Apps
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Ajax
AjaxAjax
Ajax
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Ajax
AjaxAjax
Ajax
 

Plus de s_pradeep

Plus de s_pradeep (20)

Aish Pink Panther
Aish Pink PantherAish Pink Panther
Aish Pink Panther
 
Shriya
ShriyaShriya
Shriya
 
Bhool Bhulaiya
Bhool BhulaiyaBhool Bhulaiya
Bhool Bhulaiya
 
T20 World Cup Final Photos
T20 World Cup Final PhotosT20 World Cup Final Photos
T20 World Cup Final Photos
 
Football Strategies
Football StrategiesFootball Strategies
Football Strategies
 
Amby Valley City
Amby Valley CityAmby Valley City
Amby Valley City
 
Parvathi Melton
Parvathi MeltonParvathi Melton
Parvathi Melton
 
Abhishek and Aishwarya At IIFA 2007
Abhishek and Aishwarya At IIFA 2007Abhishek and Aishwarya At IIFA 2007
Abhishek and Aishwarya At IIFA 2007
 
IIFA 2007 Awards
IIFA 2007 AwardsIIFA 2007 Awards
IIFA 2007 Awards
 
Maria Sharapova
Maria SharapovaMaria Sharapova
Maria Sharapova
 
Golden Smile - Perizaad Zorabian
Golden Smile - Perizaad ZorabianGolden Smile - Perizaad Zorabian
Golden Smile - Perizaad Zorabian
 
South Indian Actress Poonam Bajwa
South Indian Actress Poonam BajwaSouth Indian Actress Poonam Bajwa
South Indian Actress Poonam Bajwa
 
Trisha In Bheema
Trisha In BheemaTrisha In Bheema
Trisha In Bheema
 
Nayanthara
NayantharaNayanthara
Nayanthara
 
Aishwarya At French Open 2007
Aishwarya At French Open 2007Aishwarya At French Open 2007
Aishwarya At French Open 2007
 
Bollywood Beauties
Bollywood BeautiesBollywood Beauties
Bollywood Beauties
 
Vinod Kambli's Wife
Vinod Kambli's WifeVinod Kambli's Wife
Vinod Kambli's Wife
 
Miss Universe 2007 Bikini Round
Miss Universe 2007 Bikini RoundMiss Universe 2007 Bikini Round
Miss Universe 2007 Bikini Round
 
Peek Into Bollywood
Peek Into BollywoodPeek Into Bollywood
Peek Into Bollywood
 
Bollywood Babes
Bollywood BabesBollywood Babes
Bollywood Babes
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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...
 
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
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Building Applications Using Ajax

  • 2. What is AJAX? AJAX = Asynchronous JavaScript And XML Is a web development technique used for creating faster, interactive web applications.
  • 3. Who uses AJAX? Google maps Gmail Google Suggest Flickr del.icio.us Meebo and many more…
  • 4. How AJAX is different
  • 5. Need for AJAX To increase web's interactivity, speed and usability Issues with classic web applications * Almost all processing is done on server * High latency * Low interactivity
  • 6. Benefits of Using AJAX Enhance your sites by allowing quicker access to data. Reduce the amount of bandwidth used in data presentation. Make a web application that feels more like a native application.
  • 7. AJAX Workarounds Hidden IFRAME <SCRIPT> src hack Cookies
  • 8. Where to use AJAX Anywhere you have a search box, adding Google suggest functionality. Pages where you have a multi-step process. When working with large or highly interdependent datasets.
  • 9. Simple Ajax Application : How To Create a request object Make the request Handle the response
  • 10. Create a request object if browser is mozilla or safari or opera then create a new XMLHttpRequest otherwise if browser is IE create a new ActiveXObject otherwise error - browser does not support XMLHttpRequest IE 5,5.5,6 implement XHR as an ActiveX object (Msxml2.XMLHTTP/Microsoft.XMLHTTP) Mozilla 1.0+, Safari 1.2+, Opera 8+, IE7 provide XMLHttpRequest natively. All XHR objects have the same methods and properties.
  • 11. Code var xhr = null; if(window.XMLHttpRequest) // Mozilla,Safari, etc. { xhr = new XMLHttpRequest(); } else if(window.ActiveXObject) // < IE 7 { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } Else { alert('Oops! Your browser does not support XMLHttpRequest'); }
  • 12. XHR Methods open(‘method’,’url’,asyncFlag) send(content) abort() getResponseHeader(“header”) setRequestHeader(“header”,”value”)
  • 13. XHR properties onreadystatechange readystate responseText responseXML status statusText
  • 14. Make the request set onreadystatechange to callback function cbProcessResponse open a request on the XHR object send the request through the XHR object “Same Site” rule “GET” or “POST” Asynchronous flag
  • 15. Code xhr.onreadystatechange=cbProcessResponse; xhr.open(’GET’,‘ajax.php’,true); function cbProcessResponse() { if(xhr.readystate==4 && xhr.status==200) { alert(xhr.responseText); } } /* readystate values 0 -> uninitialized 1 -> loading 2 -> loaded 3 -> interactive 4 -> completed */
  • 16. Handle Response: Parsing the XML // Our sample XML <?xml version=quot;1.0quot; encoding=quot;ISO-8859-1quot;?> <root> <response>OK</response> <msg>Hello World!</msg> </root> // Revised callback function function cbProcessResponse() { if(xhr.readystate==4 && xhr.status==200) { var xmlDoc = xhr.responseXML.documentElement; var s = x.getElementsByTagName('response')[0].firstChild.data; var m = x.getElementsByTagName('msg')[0].firstChild.data; alert(‘Response Code:’+s+’nMessage: ‘+m) } }
  • 17. Enter JSON JavaScript Object Notation JSON is a lightweight data-interchange format. JSON data are slightly simpler and slightly more in line with the rest of the JavaScript language than scripts for XML data. Find more about JSON at http://json.org //sample JSON { response: ‘OK’, msg: ‘Hello World’ }
  • 18. JSON How? JSON can be generated by all the popular server-side languages. Native/Library Support // Revised callback function to use JSON function cbProcessResponse() { if(xhr.readystate==4 && xhr.status==200) { var jsonData = eval(‘(‘+xhr.responseText+’)’); var s = jsonData.response; // easy ;-) var m = jsonData.msg; alert(‘Response Code:’+s+’nMessage: ‘+m) } } Doesn’t that look simpler?
  • 19. Frameworks A framework is a re-usable design for a software system with built-in generic functions for performing repetitive, natively unsupported operations. The Prototype JavaScript Framework is a JavaScript framework that provides an Ajax framework and other utilities. Download from http://prototypejs.org Others: YUI, Dojo, jQuery, mooTools
  • 20. Using Prototype.js Prototype provides the Ajax object to abstract the different browsers. Ajax.Request() Ajax.Updater(container, url[, options]) var pars = 'topic=ajax&framework=pjs'; Var url = '/cgi-bin/myAjaxHandler.cgi'; var myAjax = new Ajax.Request(url,{ method: quot;postquot;, // get/post parameters: pars, onComplete: cbProcessResponse // Our old callback function }); Ajax.PeriodicalUpdater(container, url[, options])
  • 21. Tips Don't overuse AJAX, the usability requirements for JavaScript applications are quite different than the requirements for regular web pages. Escape content sent to the server. Use AJAX activity indicators. http://www.napyfab.com/ajax-indicators/
  • 22. Debugging AJAX Always test your PHP/Server-side code before integrating it with the JavaScript side. Always check xhr.status Use FireBug to pin-point errors, and trace performance bottle-necks. Download from http://www.getfirebug.com/
  • 23. Resources AJAXIAN - http://ajaxian.com AJAX info - http://ajaxinfo.com AJAX Lesson - http://ajaxlessons.com Go4Expert - http://go4expert.com
  • 24. Thanks! Hussain Fakhruddin Teknowledge Software The wonderful audience.