Commit 17c5dd81 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

9780596101800

0 → 120000
+1 −0
Changes for 9780596101800: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
9780596101800
 No newline at end of file

README.md

0 → 100644
+15 −0
Changes for README.md: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
## Example files for the title:  
  
# Ajax Design Patterns, by Michael Mahemoff
  
[![Ajax Design Patterns, by Michael Mahemoff](http://akamaicovers.oreilly.com/images/9780596101800/cat.gif)](https://www.safaribooksonline.com/library/view/title/0596101805//)
  
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
  
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
  
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
  
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
  
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.

example_code/appa.txt

0 → 100644
+29 −0
Changes for example_code/appa.txt: 29 added lines, 0 removed lines.
Original line number Diff line number Diff line
appendix: Ajax Frameworks and Libraries
==================

    var node = doc.groceries.frozen[0].pizza[0].size;
    var node = doc.documentElement.firstChild.firstChild.getAttribute("size");

    
    
====================================

    params = document.myForm;
    http( "POST" , "remote.cfc?method=dosomething", my_callback , params );

    
    
====================================

params = document.myForm;
http( "POST" , "remote.cfc?method=dosomething", my_callback, params );

    
    
====================================

(export-function #'my-function)

    
    
==================
 No newline at end of file

example_code/appb.txt

0 → 100644
+116 −0
Changes for example_code/appb.txt: 116 added lines, 0 removed lines.
Original line number Diff line number Diff line
appendix: Setting Up the Code Examples
==================

INSTALLING PHP
==============

* If you don't have it already, install PHP5 and integrate with Apache (or
  another web server). The demos rely on the PHP5 OO features, and won't work
  with PHP4 or below.

  There are various installers available that will create an "AMP" (Apache,
  PHP, and MySQL) setup for you (You'll need MySQL for the wiki demo - see
  below). e.g. XAMPP for all major platforms
  (http://www.apachefriends.org/en/xampp.html).  For Apple, consider
  http://www.entropy.ch/software/macosx/php/. For Linux, you may try the
  appropriate Redhat/Debian packages. Alternatively, try the compilation
  instructions at http://dan.drydog.com/apache2php.html.

SETTING UP AJAX DEMOS
=====================

* Unzip the package to a temporary location and copy run/, tutorial/, and
  records/ to the apache document root. Assuming the doc root is
  /apache/document/root:

    cp run tutorial records /apache/document/root.

  (Alternatively, if you have sufficient access, set up a new virtual host in
  apache's httpd.conf and point it to the root of the unzipped directory,
  ajaxdemos/).

* Ensure the server can write to (the initially empty) records/ directory. The
  easiest (though not the most secure) way is:

    chmod 777 apache/document/root/records

* Open up run/.htaccess and follow instructions there to set the library path.

* Finished! Visit http://localhost/run/ and http://localhost/tutorial. If you
  can access http://localhost/run/index.phtml but not http://localhost/run/,
  read the following note.

NOTE ON CONFIGURATION: You hopefully won't need any configuration because
run/.htaccess and tutorial/.htaccess contain the relevant settings. But some
apache installations will ignore those settings (depending on the AllowOverride
directive), so be ready to transfer some of the contents of run/.htaccess into
httpd.conf.  (run/.htaccess is a superset of tutorial/.htaccess.) Specifically,
modify the existing DirectoryIndex directive to include index.phtml, and add a
new type for phtml as in .htaccess. If the PHP include_path isn't working,
you'll probably need to modify it in php.ini according to the setting in
.htaccess.

SETTING UP THE WIKI DATABASE
============================

NOTE: The wiki demo and its refactorings are the only demos that require a
database. The setup isn't particularly difficult, but if you don't want to mess
with MySQL, you can still run all the other demos.

* Install MySQL if necessary
* Prepare for database access.
  * Enter mysql as power user, e.g.:
          mysql -u root
  * Create "ajaxify_wiki" power user with password "ajaxify_wiki", e.g.:
      GRANT ALL PRIVILEGES ON *.* TO 'ajaxify_wiki'@''localhost'
          IDENTIFIED BY 'ajaxify_wiki';
  * If you'd prefer to use an existing account instead, set the details in
    Model/DAO.php for any wiki demo you wish to run.
* Run run/wiki/Model/freshDB.sh. You only need to do this once, as the tables
  can be shared by all versions of the wiki. NOTE: Ensure your command-line
  path is set up so that "php" will resolve to php5.
* Point your browser at the wiki, e.g. http://localhost/run/wiki/, and you
  should see three fresh messages.

TROUBLESHOOTING
===============
If you run into any problems:
* Check the section below, as some demos require some extra setup.
* Try the tutorial demo first. It's less error-prone because there's no library
  path involved.
* Verify file permissions are correct. The easiest way is to run "chmod 755
  document/root". In addition, ensure the records/ directory is writable.
* For the wiki, manually check the database is ready and can be accessed with
  the settings in DAO.php.
* Verify your PHP setup - create a file with "<? php_info ?>" and see if you
  can access it from the browser.
* Ensure you're using PHP 5 (or later).
* Check that you can run a test file, with both .php and .phtml suffixes.
* Check that index.phtml is recognised as a valid directory index. (Check this
  by visiting path/index.phtml instead of just path/.)
* Check that you set the library in .htaccess.
* Check remoting is working as expected with a traffic sniffing tool. (See
  those listed in the Traffic Sniffing pattern).
* Inspect log files. Your PHP log might be different to your Apache error log,
  depending on your setup.
* If problems persist, mail michael@mahemoff.com.

DEMOS REQUIRING EXTRA SETUP
===========================

These demos won't work unless you do some extra setup.

* As mentioned earlier, all the wiki demos (/wiki/..) (but nothing else) require a
MySQL database.
* For all portal (/portal/..) and reader (/reader/..) demos, you need net
  access. For the portal synclinks demo (/run/portal/drilldown/syncLinks/), you
  also need to run prepareDrilldown.php first.
* For the shop demo, if you want to run the whole lazy registration process,
  you'll need some form
* For the progress indicator in the Ajaxagram tutorial
  (/tutorial/ajaxagram/..), you either need to run it with net access, or
  change the image source in index.html to point to "/resources/progress.gif".

    
    
==================
 No newline at end of file

example_code/ch02.txt

0 → 100644
+468 −0
Changes for example_code/ch02.txt: 468 added lines, 0 removed lines.
Original line number Diff line number Diff line
chapter: A Pattern-Led Tutorial
==================

 cd /apache/docroot (substitute your own document root)
 mkdir tutorial
 cd tutorial
 mkdir display remoting dynamic

    
    
====================================

  <html>

  <head>
    <title>AjaxPatterns.org - Tutorial</title>
    <script type="text/javascript" src="tutorial.js"></script>
  </head>

  <body>

    <h1>AjaxPatterns Tutorial</h1>

    <div id="sandbox">
    </div>

  </body>

    
    
====================================

  window.onload = function( ) {
    var greeting = document.createElement("span");
    greeting.style.backgroundColor = "yellow";
    greeting.innerHTML = "Hello World!";
    document.getElementById("sandbox").appendChild(greeting);
  }

    
    
====================================

  <div id="sandbox">
    <span style="background-color:yellow;">Hello World!</span>
  </div>

    
    
====================================

  function $(id) { return document.getElementById(id); }

    
    
====================================

  $("sandbox").appendChild(greeting);

    
    
====================================

  window.onload = function( ) {

    var greeting = document.createElement("span");
    greeting.style.backgroundColor = "yellow";
    greeting.innerHTMLtutorialinnerHTML 
innerHTML 
 = "Hello World!";
    $("sandbox").appendChild(greeting);

    $("sandbox").appendChild(document.createElement("hr"));
    var link = document.createElement("a");
    link.href = "http://ajaxpatterns.org";
    link.appendChild(document.createTextNode("More Ajax Stuff ..."));
    $("sandbox").appendChild(link);
  }

  function $(id) { return document.getElementById(id); }

    
    
====================================

  <h2>This is message.html</h2>

  and there's <strong>some markup</strong> here<br/>
  as well as an <a href="http://ajaxpatterns.org">AjaxPatterns link</a>.

    
    
====================================

  function createXMLHttpRequest( ) {
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
    try { return new XMLHttpRequest( ); } catch(e) {}
    alert("XMLHttpRequest not supported");
    return null;
  }

    
    
====================================

  function $(id) { return document.getElementById(id); }

    
    
====================================

  window.onload = function( ) {
    var xhr = createXMLHttpRequest( );
    xhr.onreadystatechange = function( ) {
      if (xhr.readyState==4) { // Request is finished
        if (xhr.status==200) {
          $("sandbox").innerHTML = "Retrieved from server ...<hr/>";
          $("sandbox").innerHTML += xhr.responseText;
        } else {
          alert("Message returned, but with error status.");
        }
      }
    }
    xhr.open("GET", "message.html", true);
    xhr.send(null);
  }

    
    
====================================

  function $(id) { return document.getElementById(id); }

    
    
====================================

  window.onload = function( ) {
      $("sandbox").innerHTML = "Click Here!<br/>";
    };
  }

    
    
====================================

  window.onload = function( ) {

    $("sandbox").innerHTML = "Click Here!<br/>";

    $("sandbox").onclick = function(ev) {

      ev = ev || window.event;
      $("sandbox").innerHTML =
      Clicked at " + new Date() + ". Event: " + ev + ";

      for (property in ev) {
        var message = "Property " + property + ": " + ev[property] + ";
        $("sandbox").innerHTML += message;
        }

      };

    
    
====================================

  mkdir tutorial
  cd tutorial
  mkdir ajaxagram

    
    
====================================

  <?

    /* Cleans input word and passes into findAnagramsRecursive */
    function findAnagrams($word) {
      $sorted = str_split(filterInput($word));
      sort($sorted);
      return findAnagramsRecursive(implode($sorted));
    }

    /* Convert to lowercase and only include letters */
    function filterInput($word) {
      $word = strtolower($word);
      $word = ereg_replace("[^a-z]","", $word);
      return $word;
    }

    /* Assumes $word is sorted */
    function findAnagramsRecursive($word) {

      if (strlen($word)==0) { return array( ); }
      if (strlen($word)==1) { return array($word); }

      // For each character in the word, extract it and find all anagrams
      // where it's the first character.
      $anagrams = array( );
      for ($pos=0; $pos<strlen($word); $pos++) {

        $extractedChar = substr($word,$pos,1);
        // If same as previous, don't process any further as it will only
        // create duplicates (this is the only check against duplicates,
        // since the word is sorted).
        $sameAsPreviousChar =
          ($pos > 0 && $extractedChar==substr($word,$pos-1,1));

        if (!$sameAsPreviousChar) {
          $remaining = removeCharAt($word, $pos);
          $anagramsOfRemaining = findAnagramsRecursive($remaining);
          foreach ($anagramsOfRemaining as $anagramOfRemaining) {
            array_push($anagrams, $extractedChar . $anagramOfRemaining);
          }
        }
      }

      return $anagrams;

    }

    /* Return word without character at pos */
    function removeCharAt($word, $pos) {
      return substr($word, 0, $pos) . substr($word, $pos+1);
    }

  ?>

    
    
====================================

  <?
    require_once("anagram.php");

    $word = array_key_exists('word', $_GET) ? $_GET['word'] : "";
    $anagramsArray = findAnagrams($word);
    print implode(",", $anagramsArray);
  ?>

    
    
====================================

  <html>

  <head>
    <title>AjaxPatterns.org - Ajaxagram (Basic Ajax Version)</title>
    <script type="text/javascript" src="ajaxagram.js">tutorialAjaxagramajaxagram.js 
ajaxagram.js 
</script>
  </head>

  <body>

    <h1>Ajaxagram (Basic Ajax Version)</h1>

    <div>
      <input type="text" id="word" size="5" maxlength="5" />
      <button id="findAnagrams">Find Anagrams!</button>
    </div>

    <div id="results">
    </div>

  </body>

    
    
====================================

// -- Generic functions --------------------------------------------------

function createXMLHttpRequest( ) {
      try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
      try { return new XMLHttpRequest( ); } catch(e) {}
      alert("XMLHttpRequest not supported");
      return null;
}

function $(id) {
  return document.getElementById(id);
}

    
    
====================================

  window.onload = function( ) {
    $("findAnagrams").onclick = function( ) {
      submitWord( );
    }
  }

    
    
====================================

  function submitWord( ) {
    var xhr = createXMLHttpRequest( );
    xhr.onreadystatechange = function( ) {
      if (xhr.readyState==4) { // Request is finished
        if (xhr.status==200) {
          var anagramsCSV = xhr.responseText;
          updateAnagramsDisplay(anagramsCSV);
        } else {
          alert("An error occurred.");
        }
      }
    }
    var word = $("word").value;
    xhr.open("GET", "anagrams.phtml?word="+word, true);
    xhr.send(null);
  }

    
    
====================================

  function updateAnagramsDisplay(anagramsCSV) {
    $("results").innerHTML = "";
    var anagrams = anagramsCSV.split(",");
    for (var i=0; i<anagrams.length; i++) {
      $("results").innerHTML += anagrams[i] + "<br/>";
    }
  }

    
    
====================================

  window.onload = function( ) {
    $("word").onkeyup = function( ) {
      submitWord( );
    }
  }

    
    
====================================

  <div>
    <input type="text" id="word" size="5" maxlength="5" />
  </div>

    
    
====================================

  <div>
    <input type="text" id="word" size="5" maxlength="5" />
  </div>

  <img id="progress"
   src="http://ajaxify.com/tutorial/resources/progress.gif"
         class="notWaiting"/>

    
    
====================================

  <head>
    <title>AjaxPatterns.org - Ajaxagram (Basic Ajax Version)</title>
    <script type="text/javascript" src="ajaxagram.js"></script>
    <link rel="stylesheet" type="text/css" href="ajaxagram.css"/>
  </head>

    
    
====================================

  .waiting {
    visibility: visible;
  }

  .notWaiting {
    visibility: hidden;
  }

    
    
====================================

  function submitWord( ) {
    // Show progress indicator and clear existing results
    $("progress").className = "waiting";
    $("results").innerHTML = "";
    ...
  }

  function updateAnagramsDisplay(anagramsCSV) {
    $("progress").className = "notWaiting";
    var anagrams = anagramsCSV.split(",");
    ...
  }

    
    
====================================

  // Caller-friendly front-end to fadeLoop
  function fade( ) {
    fadeLoop(0);
  }

  function fadeLoop(nextBluePercent) {
    $("results").style.backgroundColor = "rgb(100%, 100%, "+nextBluePercent+"%)";
    nextBluePercent += 10;
    if (nextBluePercent<=100) {
      setTimeout("fadeLoop("+nextBluePercent+")", 100);
    }
  }

    
    
====================================

  function updateAnagramsDisplay(anagramsCSV) {
    $("progress").className = "notWaiting";
    fade(0);
    ...
  }

    
    
====================================

  var submitTimer;

  window.onload = function( ) {
    $("word").onkeyup = function( ) {
      clearTimeout(submitTimer); // Clears any previously
scheduled submission
    }
  }

    
    
====================================

  <head>
  <title>AjaxPatterns.org - Ajaxagram ()</title>
  <script type="text/javascript" src="ajaxagram.js"></script>
  <script type="text/javascript" src="http://ajaxify.com/tutorial/resources/
       ajaxCaller.js"></script>
 <link rel="stylesheet" type="text/css" href="ajaxagram.css" />
</head>

    
    
====================================

  function submitWord( ) {

    // Show progress indicator and clear existing results
    $("progress").className = "waiting";
    $("results").innerHTML = "";

    var word = $("word").value;
    ajaxCaller.getPlainText("anagrams.phtml?word="+word,updateAnagramsDisplay);
  }

    
    
==================
 No newline at end of file
Loading