SlideShare a Scribd company logo
1 of 46
Ajax and Web Services

         Mark Pruett

          Dominion




1
Ajax started as an acronym:

    Asynchronous Javascript and XML




2
Web Services




3
REST

    Representational State Transfer




4
SOAP

    Simple Object Access Protocol




5
Question:

    Are news feeds web services?




6
A Simple Ajax / Web Service Example




7
Program Specification
    quot;Write an application that reads the answer to
    the question, quot;What's the meaning of life, the
    universe, and everythingquot;, stored on our
    server, and displays it in the user's web
    browser.quot;




8
Meaning of Life, the Universe,
          and Everything:

                 42




9
Store the value 42 in a text file:

     MeaningOfLifeTheUniverseAndEverything.txt




10
#!/usr/bin/perl
     use strict;

     my $ANSWERS_DIR = quot;/var/www/htmlquot;;

     # Get the question.
     my $question;
     my @parts = split (quot;", $ENV{quot;QUERY_STRINGquot;});
     foreach my $lrval (@parts) {
         if ($lrval =~ /^question=(.+)$/) {
             $question = $1;
             $question =~ s/%([dA-Fa-f]{2})/pack (quot;Cquot;, hex ($1))/eg ;
         }
     }

     # Get the answer.
     my $answer = get_answer_to ($question);

     # Return the answer.
     print quot;Content-type: text/htmlnnquot;;
     print quot;$answernquot;;

     sub get_answer_to {
         my ($question) = @_;
         my $answer = quot;I didn't understand the question ($question).quot;;

         if ($question eq quot;What is the meaning of life, the universe, and everything?quot;) {
             open (my $IFILE, quot;< $ANSWERS_DIR/MeaningOfLifeTheUniverseAndEverything.txtquot;);
             $answer = <$IFILE>;
             close $IFILE;
         }

         return $answer;
     }




11
<HTML>
     <HEAD>
     <TITLE>Question</TITLE>
     <SCRIPT language=quot;Javascriptquot;>
     function get_answer () {
         var xmlhttp = create_xmlhttp ();

         var url = quot;/cgi-bin/svc/answers.cgi?quot;;
         var parms = quot;question=What%20is%20the%20meaning%20of%20life,quot;
                   + quot;%20the%20universe,%20and%20everything?quot;;

         xmlhttp.onreadystatechange = function () {
             if (xmlhttp.readyState == 4) {
                 var span = document.getElementById (quot;spanAnswerquot;);
                 span.innerHTML = xmlhttp.responseText;
             }
         }

         xmlhttp.open(quot;GETquot;, url + parms, true);
         xmlhttp.send (null);
     }

     function create_xmlhttp () {
        // 25 lines omitted...
     }
     </SCRIPT>
     <BODY>
       <form id=quot;frmQuestionquot;>
         What is the meaning of life, the universe, and everything?
         <input type=quot;buttonquot; value=quot;Get Answerquot; onclick=quot;get_answer();quot;>
         <span id=quot;spanAnswerquot;>
         </span>
       </form>
     </BODY>
     </HTML>



12
13
14
A Corporate Information Architecture Diagram




15
The Evolution of Ajax Use
       Send back a chunk of HTML – dump into DIV tag
     !


       Send back delimited text – parse it and dynamically
     !


       update the page
       Send back XML – parse dynamically
     !


       Some people move to JSON
     !




16
Trade-Off #0

     Ajax vs. Flex vs. Flash vs. Silverlight




17
Trade-Off #1

       Toolkits




18
Toolkits:
         prototype
     !


         Dojo
     !


         GWT (Google)
     !


         Atlas (Microsoft)
     !


         Rico
     !


         Zimbra
     !


         DWR
     !


         many, many, more
     !




19
Internet Explorer – Error on Page




20
Internet Explorer – Script Error Dialog




21
Trade-Off #2

     SOAP vs. REST




22
SOAP

     Simple Object Access Protocol




23
A SOAP Envelope for Google Search API
     <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
     <SOAP-ENV:Envelope
         xmlns:SOAP-ENV=quot;http://schemas.xmlsoap.org/soap/envelope/quot;
         xmlns:xsi=quot;http://www.w3.org/1999/XMLSchema-instancequot;
         xmlns:xsd=quot;http://www.w3.org/1999/XMLSchemaquot;>
     <SOAP-ENV:Body>
       <ns1:doGoogleSearch xmlns:ns1=quot;urn:GoogleSearchquot;>
         <key xsi:type=quot;xsd:stringquot;>YOUR_GOOGLE_KEY</key>'
         <q xsi:type=quot;xsd:stringquot;>ajax javascript</q>
         <start xsi:type=quot;xsd:intquot;>0</start>
         <maxResults xsi:type=quot;xsd:intquot;>5</maxResults>
         <filter xsi:type=quot;xsd:booleanquot;>true</filter>
         <restrict xsi:type=quot;xsd:stringquot;></restrict>
         <safeSearch xsi:type=quot;xsd:booleanquot;>false</safeSearch>
         <lr xsi:type=quot;xsd:stringquot;></lr>
         <ie xsi:type=quot;xsd:stringquot;>latin1</ie>
         <oe xsi:type=quot;xsd:stringquot;>latin1</oe>
       </ns1:doGoogleSearch>
     </SOAP-ENV:Body></SOAP-ENV:Envelope>




24
Javascript Ajax SOAP Search (the hard way)
     function search () {
       var query = document.getElementById(quot;txtSearchquot;).value;
       var soap_env =
          '<?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>'
          + quot;<SOAP-ENV:Envelopequot;
          ...
          + '<SOAP-ENV:Body>'
          + '<ns1:doGoogleSearch xmlns:ns1=quot;urn:GoogleSearchquot;>'
          + '<key xsi:type=quot;xsd:stringquot;>MY_GOOGLE_KEY</key>'
          + '<q xsi:type=quot;xsd:stringquot;>' + query + '</q>'
          ...
          + '</ns1:doGoogleSearch>'
          + '</SOAP-ENV:Body></SOAP-ENV:Envelope>';
       var ajax = new Ajax (quot;/gsearchquot;, soap_env, quot;POSTquot;,
                            function () {
                               if (ajax.req.status == 200) {
                                 google2html (quot;divOutputquot;, ajax.req.responseXML);
                               }
                            }
                            );
       // Google's SOAP server requires this header.
       ajax.setRequestHeader(quot;Content-Typequot;, quot;text/xmlquot;);

         // Send the request to the SOAP server.
         ajax.request ();
     }



25
REST

     Representational State Transfer




26
REST

         Uses HTTP GET and POST
     !


         Also uses HTTP PUT and DELETE
     !




27
REST
     HTTP Method   HTTP Status Codes   REST Web Service Operation


     GET           200 OK              Retrieve a representation of a
                   410 Gone            resource from the server.


     PUT           200 OK              Create a new resource on the server.
                   400 Bad Request


     POST          200 OK              Update an existing resource.
                   410 Gone


     DELETE        200 OK              Delete and existing service.
                   204 No Content

28
Trade-Off #3

     Asynchronous vs. Synchronous




29
Trade-Off #4

     XML vs. JSON vs. CSV




30
XML
     <person>
       <firstName>John</firstName>
       <lastName>Smith</lastName>
       <address>
         <city>New York, NY</city>
         <zipCode>10021</zipCode>
         <streetAddress>21 2nd Street</streetAddress>
       </address>
       <phoneNumbers>
         <number>212 732-1234</number>
         <number>646 123-4567</number>
       </phoneNumbers>
     </person>




31
XML


     If you want the XMLHttpRequest responseXML property

     make sure your server uses the proper response header:

                 Content-type: text/xml




32
JSON
     {
         quot;firstNamequot;: quot;Johnquot;,
         quot;lastNamequot;: quot;Smithquot;,
         quot;addressquot;: {
             quot;cityquot;: quot;New York, NYquot;,
             quot;zipCodequot;: 10021,
             quot;streetAddressquot;: quot;21 2nd Streetquot;
         },
         quot;phoneNumbersquot;: [
             quot;212 732-1234quot;,
             quot;646 123-4567quot;
         ]
     }




33
JSON
     var my_json;
     ...
     my_json = eval (quot;(quot; + http_request.responseText + quot;)quot;);
     ...
     alert (my_json.firstName + quot; quot; + my_json.lastName);




34
CSV
     quot;Johnquot;,quot;Smithquot;,quot;21 2nd Streetquot;,quot;New York, NYquot;,10021,
     quot;212 732-1234quot;,quot;646 123-4567quot;




35
Trade-Off #5

     XMLHttpRequest vs. The Script Tag Hack
                      or
           What To Do About Proxies



36
The Cross-Domain Problem




37
Apache ProxyPass
     ProxyPass          pattern   substitution
     ProxyPassReverse   pattern   substitution


     ProxyPass        /ysearch/ http://api.search.yahoo.com/WebSearchService/V1/
     ProxyPassReverse /ysearch/ http://api.search.yahoo.com/WebSearchService/V1/




38
Apache ProxyPass
     Let's say your application is running on http://www.example.com. With
     these two proxy rules in place, any request to:
     http://www.example.com/ysearch/

     is automatically redirected to:
     http://api.search.yahoo.com/WebSearchService/V1/




39
A CGI Script as Proxy
     #!/usr/bin/perl
     #---------------------------------------------------------
     # A simple, specific, proxy as a standalone server script.
     #---------------------------------------------------------

     use strict;
     use LWP::Simple;

     # Constants
     my $REAL_URL = quot;http://api.search.yahoo.com/WebSearchService/V1/webSearchquot;;
     my $APPID = quot;Perl+API+install+testquot;;

     # Append the Yahoo! Search appid to the parameter string.
     my $parameters = $ENV{QUERY_STRING} . quot;&appid=$APPIDquot;;

     # Retrieve data from the Yahoo! server using the Perl LWP module.
     my $data = get quot;$REAL_URL?$parametersquot;;

     # Output the HTTP header followed by the retrieved XML.
     # Anything a server CGI script sends to standard output
     # is sent back to the browser.
     print quot;Content-type: text/xmlnnquot;;
     print $data;




40
The Javascript SCRIPT tag hack
     <script language=quot;Javascriptquot; src=quot;http://random.server/somescript.jsquot;>




41
A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content
     // The YPipesJSON constructor
     function YPipesJSON (title, ypipes_url, div_name, obj_name) {
       this.title = title;
       this.url = ypipes_url + quot;&_callback=quot; + obj_name + quot;.jsonHandlerquot;;
       this.div_name = div_name;
     }
     // The requestJSON method: builds script tag - launches our request to the server.
     YPipesJSON.prototype.requestJSON = function () {
       var head = document.getElementsByTagName(quot;headquot;).item(0);
       var script = document.createElement (quot;scriptquot;);
       script.src = this.url;
       head.appendChild (script);
     }
     // The jsonHandler method: this is our callback function.
     // It's called when the JSON is returned to our browser from Yahoo!.
     YPipesJSON.prototype.jsonHandler = function (json) {
       var div = document.getElementById (this.div_name);
       var desc_limit = 200;
       var html = quot;<b>quot; + this.title + quot;</b><br>nquot;;;
       for (var i=0; i < json.count; i++) {
          html += quot;<a href='quot; + json.value.items[i].link + quot;'>quot;;
          // Some formatting code deleted...
       }
         html += desc + quot;<p>nquot;;
       }
       div.innerHTML = html;
     }

42
A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content



             http://pipes.yahoo.com/pipes/pipe.run?
             textinput1=linux
             &_id=lnmGDou72xGK6WDrZYQMOQ
             &_run=1
             &_render=json
             &_callback=yp1.jsonHandler




43
A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content
     ...
     <script language=quot;Javascriptquot; src=quot;ypipes_json.jsquot;></script>
     <script>
     var yp1;
     function init () {
       var url;

      url =   quot;http://pipes.yahoo.com/pipes/pipe.run?quot;
          +   quot;textinput1=linuxquot;
          +   quot;&_id=lnmGDou72xGK6WDrZYQMOQquot;
          +   quot;&_run=1quot;
          +   quot;&_render=jsonquot;;

      yp1 = new YPipesJSON (quot;O'Reilly on Linuxquot;, url, quot;target1quot;, quot;yp1quot;);
      yp1.requestJSON ();
     }
     </script>
     </head>

     <body onload=quot;init();quot;>
       <h3>Yahoo! Pipes JSON Script Tag Example</h3>
       <div id=quot;target1quot;>
         Loading...
       </div>
     </body>
     </html>


44
A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content




45
Conclusion(s)




46

More Related Content

What's hot

CouchDB Google
CouchDB GoogleCouchDB Google
CouchDB Google
Steve Souders
 
Ruby on Rails Security
Ruby on Rails SecurityRuby on Rails Security
Ruby on Rails Security
amiable_indian
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
Michael Girouard
 

What's hot (20)

Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Php assĂ­ncrono com_react_php
Php assĂ­ncrono com_react_phpPhp assĂ­ncrono com_react_php
Php assĂ­ncrono com_react_php
 
CouchDB Google
CouchDB GoogleCouchDB Google
CouchDB Google
 
Ruby on Rails Security
Ruby on Rails SecurityRuby on Rails Security
Ruby on Rails Security
 
Scalable talk notes
Scalable talk notesScalable talk notes
Scalable talk notes
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimization
 
Introducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applicationsIntroducing RaveJS: Spring Boot concepts for JavaScript applications
Introducing RaveJS: Spring Boot concepts for JavaScript applications
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tip
 
Ruby HTTP clients
Ruby HTTP clientsRuby HTTP clients
Ruby HTTP clients
 
How Flipkart scales PHP
How Flipkart scales PHPHow Flipkart scales PHP
How Flipkart scales PHP
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with Rack
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web
 
Varnish 4 cool features
Varnish 4 cool featuresVarnish 4 cool features
Varnish 4 cool features
 

Viewers also liked

Yuicss R7
Yuicss R7Yuicss R7
Yuicss R7
oscon2007
 
Os Fogel
Os FogelOs Fogel
Os Fogel
oscon2007
 
Os Tucker
Os TuckerOs Tucker
Os Tucker
oscon2007
 
Os Alrubaie
Os AlrubaieOs Alrubaie
Os Alrubaie
oscon2007
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashears
oscon2007
 
Os Kimsal
Os KimsalOs Kimsal
Os Kimsal
oscon2007
 
Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5
oscon2007
 
J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Tour
oscon2007
 

Viewers also liked (8)

Yuicss R7
Yuicss R7Yuicss R7
Yuicss R7
 
Os Fogel
Os FogelOs Fogel
Os Fogel
 
Os Tucker
Os TuckerOs Tucker
Os Tucker
 
Os Alrubaie
Os AlrubaieOs Alrubaie
Os Alrubaie
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashears
 
Os Kimsal
Os KimsalOs Kimsal
Os Kimsal
 
Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5
 
J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Tour
 

Similar to Os Pruett

Ajax
AjaxAjax
Ajax
jainaman
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
Somay Nakhal
 

Similar to Os Pruett (20)

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
AjaxAjax
Ajax
 
Cross Domain Web‹Mashups with JQuery and Google App Engine
Cross Domain Web‹Mashups with JQuery and Google App EngineCross Domain Web‹Mashups with JQuery and Google App Engine
Cross Domain Web‹Mashups with JQuery and Google App Engine
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 
huhu
huhuhuhu
huhu
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solr
 
Ajax3
Ajax3Ajax3
Ajax3
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
WebSocket JSON Hackday
WebSocket JSON HackdayWebSocket JSON Hackday
WebSocket JSON Hackday
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQuery
 
Yql && Raphaël
Yql && RaphaëlYql && Raphaël
Yql && Raphaël
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
Postman On Steroids
Postman On SteroidsPostman On Steroids
Postman On Steroids
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Security
 

More from oscon2007

Os Borger
Os BorgerOs Borger
Os Borger
oscon2007
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifm
oscon2007
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Mole
oscon2007
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swp
oscon2007
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Myths
oscon2007
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholistic
oscon2007
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillips
oscon2007
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdated
oscon2007
 
Adventures In Copyright Reform
Adventures In Copyright ReformAdventures In Copyright Reform
Adventures In Copyright Reform
oscon2007
 
Railsconf2007
Railsconf2007Railsconf2007
Railsconf2007
oscon2007
 
Oscon Mitchellbaker
Oscon MitchellbakerOscon Mitchellbaker
Oscon Mitchellbaker
oscon2007
 
Os Sharp
Os SharpOs Sharp
Os Sharp
oscon2007
 
Os Pruett Sessionnotes
Os Pruett SessionnotesOs Pruett Sessionnotes
Os Pruett Sessionnotes
oscon2007
 
Os Keyshacks
Os KeyshacksOs Keyshacks
Os Keyshacks
oscon2007
 
Os Buncetutorial
Os BuncetutorialOs Buncetutorial
Os Buncetutorial
oscon2007
 
Os Napier
Os NapierOs Napier
Os Napier
oscon2007
 
Os Treat
Os TreatOs Treat
Os Treat
oscon2007
 
Os Raible
Os RaibleOs Raible
Os Raible
oscon2007
 
Os Recordontutorial
Os RecordontutorialOs Recordontutorial
Os Recordontutorial
oscon2007
 

More from oscon2007 (19)

Os Borger
Os BorgerOs Borger
Os Borger
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifm
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Mole
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swp
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Myths
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholistic
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillips
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdated
 
Adventures In Copyright Reform
Adventures In Copyright ReformAdventures In Copyright Reform
Adventures In Copyright Reform
 
Railsconf2007
Railsconf2007Railsconf2007
Railsconf2007
 
Oscon Mitchellbaker
Oscon MitchellbakerOscon Mitchellbaker
Oscon Mitchellbaker
 
Os Sharp
Os SharpOs Sharp
Os Sharp
 
Os Pruett Sessionnotes
Os Pruett SessionnotesOs Pruett Sessionnotes
Os Pruett Sessionnotes
 
Os Keyshacks
Os KeyshacksOs Keyshacks
Os Keyshacks
 
Os Buncetutorial
Os BuncetutorialOs Buncetutorial
Os Buncetutorial
 
Os Napier
Os NapierOs Napier
Os Napier
 
Os Treat
Os TreatOs Treat
Os Treat
 
Os Raible
Os RaibleOs Raible
Os Raible
 
Os Recordontutorial
Os RecordontutorialOs Recordontutorial
Os Recordontutorial
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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 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?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 

Os Pruett

  • 1. Ajax and Web Services Mark Pruett Dominion 1
  • 2. Ajax started as an acronym: Asynchronous Javascript and XML 2
  • 4. REST Representational State Transfer 4
  • 5. SOAP Simple Object Access Protocol 5
  • 6. Question: Are news feeds web services? 6
  • 7. A Simple Ajax / Web Service Example 7
  • 8. Program Specification quot;Write an application that reads the answer to the question, quot;What's the meaning of life, the universe, and everythingquot;, stored on our server, and displays it in the user's web browser.quot; 8
  • 9. Meaning of Life, the Universe, and Everything: 42 9
  • 10. Store the value 42 in a text file: MeaningOfLifeTheUniverseAndEverything.txt 10
  • 11. #!/usr/bin/perl use strict; my $ANSWERS_DIR = quot;/var/www/htmlquot;; # Get the question. my $question; my @parts = split (quot;&quot;, $ENV{quot;QUERY_STRINGquot;}); foreach my $lrval (@parts) { if ($lrval =~ /^question=(.+)$/) { $question = $1; $question =~ s/%([dA-Fa-f]{2})/pack (quot;Cquot;, hex ($1))/eg ; } } # Get the answer. my $answer = get_answer_to ($question); # Return the answer. print quot;Content-type: text/htmlnnquot;; print quot;$answernquot;; sub get_answer_to { my ($question) = @_; my $answer = quot;I didn't understand the question ($question).quot;; if ($question eq quot;What is the meaning of life, the universe, and everything?quot;) { open (my $IFILE, quot;< $ANSWERS_DIR/MeaningOfLifeTheUniverseAndEverything.txtquot;); $answer = <$IFILE>; close $IFILE; } return $answer; } 11
  • 12. <HTML> <HEAD> <TITLE>Question</TITLE> <SCRIPT language=quot;Javascriptquot;> function get_answer () { var xmlhttp = create_xmlhttp (); var url = quot;/cgi-bin/svc/answers.cgi?quot;; var parms = quot;question=What%20is%20the%20meaning%20of%20life,quot; + quot;%20the%20universe,%20and%20everything?quot;; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { var span = document.getElementById (quot;spanAnswerquot;); span.innerHTML = xmlhttp.responseText; } } xmlhttp.open(quot;GETquot;, url + parms, true); xmlhttp.send (null); } function create_xmlhttp () { // 25 lines omitted... } </SCRIPT> <BODY> <form id=quot;frmQuestionquot;> What is the meaning of life, the universe, and everything? <input type=quot;buttonquot; value=quot;Get Answerquot; onclick=quot;get_answer();quot;> <span id=quot;spanAnswerquot;> </span> </form> </BODY> </HTML> 12
  • 13. 13
  • 14. 14
  • 15. A Corporate Information Architecture Diagram 15
  • 16. The Evolution of Ajax Use Send back a chunk of HTML – dump into DIV tag ! Send back delimited text – parse it and dynamically ! update the page Send back XML – parse dynamically ! Some people move to JSON ! 16
  • 17. Trade-Off #0 Ajax vs. Flex vs. Flash vs. Silverlight 17
  • 18. Trade-Off #1 Toolkits 18
  • 19. Toolkits: prototype ! Dojo ! GWT (Google) ! Atlas (Microsoft) ! Rico ! Zimbra ! DWR ! many, many, more ! 19
  • 20. Internet Explorer – Error on Page 20
  • 21. Internet Explorer – Script Error Dialog 21
  • 22. Trade-Off #2 SOAP vs. REST 22
  • 23. SOAP Simple Object Access Protocol 23
  • 24. A SOAP Envelope for Google Search API <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> <SOAP-ENV:Envelope xmlns:SOAP-ENV=quot;http://schemas.xmlsoap.org/soap/envelope/quot; xmlns:xsi=quot;http://www.w3.org/1999/XMLSchema-instancequot; xmlns:xsd=quot;http://www.w3.org/1999/XMLSchemaquot;> <SOAP-ENV:Body> <ns1:doGoogleSearch xmlns:ns1=quot;urn:GoogleSearchquot;> <key xsi:type=quot;xsd:stringquot;>YOUR_GOOGLE_KEY</key>' <q xsi:type=quot;xsd:stringquot;>ajax javascript</q> <start xsi:type=quot;xsd:intquot;>0</start> <maxResults xsi:type=quot;xsd:intquot;>5</maxResults> <filter xsi:type=quot;xsd:booleanquot;>true</filter> <restrict xsi:type=quot;xsd:stringquot;></restrict> <safeSearch xsi:type=quot;xsd:booleanquot;>false</safeSearch> <lr xsi:type=quot;xsd:stringquot;></lr> <ie xsi:type=quot;xsd:stringquot;>latin1</ie> <oe xsi:type=quot;xsd:stringquot;>latin1</oe> </ns1:doGoogleSearch> </SOAP-ENV:Body></SOAP-ENV:Envelope> 24
  • 25. Javascript Ajax SOAP Search (the hard way) function search () { var query = document.getElementById(quot;txtSearchquot;).value; var soap_env = '<?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>' + quot;<SOAP-ENV:Envelopequot; ... + '<SOAP-ENV:Body>' + '<ns1:doGoogleSearch xmlns:ns1=quot;urn:GoogleSearchquot;>' + '<key xsi:type=quot;xsd:stringquot;>MY_GOOGLE_KEY</key>' + '<q xsi:type=quot;xsd:stringquot;>' + query + '</q>' ... + '</ns1:doGoogleSearch>' + '</SOAP-ENV:Body></SOAP-ENV:Envelope>'; var ajax = new Ajax (quot;/gsearchquot;, soap_env, quot;POSTquot;, function () { if (ajax.req.status == 200) { google2html (quot;divOutputquot;, ajax.req.responseXML); } } ); // Google's SOAP server requires this header. ajax.setRequestHeader(quot;Content-Typequot;, quot;text/xmlquot;); // Send the request to the SOAP server. ajax.request (); } 25
  • 26. REST Representational State Transfer 26
  • 27. REST Uses HTTP GET and POST ! Also uses HTTP PUT and DELETE ! 27
  • 28. REST HTTP Method HTTP Status Codes REST Web Service Operation GET 200 OK Retrieve a representation of a 410 Gone resource from the server. PUT 200 OK Create a new resource on the server. 400 Bad Request POST 200 OK Update an existing resource. 410 Gone DELETE 200 OK Delete and existing service. 204 No Content 28
  • 29. Trade-Off #3 Asynchronous vs. Synchronous 29
  • 30. Trade-Off #4 XML vs. JSON vs. CSV 30
  • 31. XML <person> <firstName>John</firstName> <lastName>Smith</lastName> <address> <city>New York, NY</city> <zipCode>10021</zipCode> <streetAddress>21 2nd Street</streetAddress> </address> <phoneNumbers> <number>212 732-1234</number> <number>646 123-4567</number> </phoneNumbers> </person> 31
  • 32. XML If you want the XMLHttpRequest responseXML property make sure your server uses the proper response header: Content-type: text/xml 32
  • 33. JSON { quot;firstNamequot;: quot;Johnquot;, quot;lastNamequot;: quot;Smithquot;, quot;addressquot;: { quot;cityquot;: quot;New York, NYquot;, quot;zipCodequot;: 10021, quot;streetAddressquot;: quot;21 2nd Streetquot; }, quot;phoneNumbersquot;: [ quot;212 732-1234quot;, quot;646 123-4567quot; ] } 33
  • 34. JSON var my_json; ... my_json = eval (quot;(quot; + http_request.responseText + quot;)quot;); ... alert (my_json.firstName + quot; quot; + my_json.lastName); 34
  • 35. CSV quot;Johnquot;,quot;Smithquot;,quot;21 2nd Streetquot;,quot;New York, NYquot;,10021, quot;212 732-1234quot;,quot;646 123-4567quot; 35
  • 36. Trade-Off #5 XMLHttpRequest vs. The Script Tag Hack or What To Do About Proxies 36
  • 38. Apache ProxyPass ProxyPass pattern substitution ProxyPassReverse pattern substitution ProxyPass /ysearch/ http://api.search.yahoo.com/WebSearchService/V1/ ProxyPassReverse /ysearch/ http://api.search.yahoo.com/WebSearchService/V1/ 38
  • 39. Apache ProxyPass Let's say your application is running on http://www.example.com. With these two proxy rules in place, any request to: http://www.example.com/ysearch/ is automatically redirected to: http://api.search.yahoo.com/WebSearchService/V1/ 39
  • 40. A CGI Script as Proxy #!/usr/bin/perl #--------------------------------------------------------- # A simple, specific, proxy as a standalone server script. #--------------------------------------------------------- use strict; use LWP::Simple; # Constants my $REAL_URL = quot;http://api.search.yahoo.com/WebSearchService/V1/webSearchquot;; my $APPID = quot;Perl+API+install+testquot;; # Append the Yahoo! Search appid to the parameter string. my $parameters = $ENV{QUERY_STRING} . quot;&appid=$APPIDquot;; # Retrieve data from the Yahoo! server using the Perl LWP module. my $data = get quot;$REAL_URL?$parametersquot;; # Output the HTTP header followed by the retrieved XML. # Anything a server CGI script sends to standard output # is sent back to the browser. print quot;Content-type: text/xmlnnquot;; print $data; 40
  • 41. The Javascript SCRIPT tag hack <script language=quot;Javascriptquot; src=quot;http://random.server/somescript.jsquot;> 41
  • 42. A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content // The YPipesJSON constructor function YPipesJSON (title, ypipes_url, div_name, obj_name) { this.title = title; this.url = ypipes_url + quot;&_callback=quot; + obj_name + quot;.jsonHandlerquot;; this.div_name = div_name; } // The requestJSON method: builds script tag - launches our request to the server. YPipesJSON.prototype.requestJSON = function () { var head = document.getElementsByTagName(quot;headquot;).item(0); var script = document.createElement (quot;scriptquot;); script.src = this.url; head.appendChild (script); } // The jsonHandler method: this is our callback function. // It's called when the JSON is returned to our browser from Yahoo!. YPipesJSON.prototype.jsonHandler = function (json) { var div = document.getElementById (this.div_name); var desc_limit = 200; var html = quot;<b>quot; + this.title + quot;</b><br>nquot;;; for (var i=0; i < json.count; i++) { html += quot;<a href='quot; + json.value.items[i].link + quot;'>quot;; // Some formatting code deleted... } html += desc + quot;<p>nquot;; } div.innerHTML = html; } 42
  • 43. A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content http://pipes.yahoo.com/pipes/pipe.run? textinput1=linux &_id=lnmGDou72xGK6WDrZYQMOQ &_run=1 &_render=json &_callback=yp1.jsonHandler 43
  • 44. A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content ... <script language=quot;Javascriptquot; src=quot;ypipes_json.jsquot;></script> <script> var yp1; function init () { var url; url = quot;http://pipes.yahoo.com/pipes/pipe.run?quot; + quot;textinput1=linuxquot; + quot;&_id=lnmGDou72xGK6WDrZYQMOQquot; + quot;&_run=1quot; + quot;&_render=jsonquot;; yp1 = new YPipesJSON (quot;O'Reilly on Linuxquot;, url, quot;target1quot;, quot;yp1quot;); yp1.requestJSON (); } </script> </head> <body onload=quot;init();quot;> <h3>Yahoo! Pipes JSON Script Tag Example</h3> <div id=quot;target1quot;> Loading... </div> </body> </html> 44
  • 45. A Script Tag Hack JS Object for “Badging” Yahoo! Pipes Content 45