TWikiAjaxContrib Examples

Code examples and demos for TWikiAjaxContrib.

Default loading indicator

Because TWiki files are served along dynamic urls we cannot use a static url for the indicator; instead we create HTML with a path to our own default loading incidator.

twiki.AjaxRequest.setDefaultIndicatorHtml(
   "<img src='%PUBURL%/%SYSTEMWEB%/TWikiAjaxContrib/indicator.gif' alt='' />"
   );

We can retrieve the loading indicator:

twiki.AjaxRequest.getDefaultIndicatorHtml();

Loading directly

function autoLoad () {
   twiki.AjaxRequest.load(
      "AUTOLOAD",
      {
         container:"autoLoadContainer",
         url:"%PUBURL%/%SYSTEMWEB%/TWikiAjaxContribExamples/test_hamlet.html?"
      });
}
addLoadEvent(autoLoad);

Demo

Autoload

Page parts / Named Sections

function showNewTopicForm(el) {

   // load javascript
   var javascriptUrl = "%SCRIPTURL{"view"}%/%SYSTEMWEB%/WebTopicCreator?skin=text"
            + ";section=" + "javascriptfunctions";
            
   twiki.AjaxRequest.load("NEWTOPICFORM_JS",
      {
         url:javascriptUrl,
         type:"script",
         cache:true
      });
      

   var containerId = "newTopicFormContainer";
   
   // remove old container if any
   twiki.HTML.deleteElementWithId(containerId);
   
   var topicName = el.innerHTML.split("<")[0];
   var newContainer = twiki.HTML.insertAfterElement(
      el,
      'div',
      '',
      {
         "id":containerId,
         "style":
            {
               "margin":"0 0 .5em 0"
            }
      }
   );
   var url = "%SCRIPTURL{"view"}%/%SYSTEMWEB%/WebTopicCreator?skin=text"
            + ";section=" + "newtopicform"
            + ";newtopic=" + topicName
            + ";parent=" + "<nop>%TOPIC%";
   twiki.AjaxRequest.load("NEWTOPICFORM",
      {
         container:containerId,
         url:url
      });
}
var myrules = {
   '.twikiNewLink a' : function(el) {
      el.onclick = function() {
         showNewTopicForm(el.parentNode);
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo

hand Click on the "new topic link question mark" at DoesNotExist in the text below to retrieve the "Create new topic" form (located at WebTopicCreator):

Good now, sit down, and tell me, he that knows, Why this same strict and most observant watch So nightly toils the subject of the land, DoesNotExist? And why such daily cast of brazen cannon, And foreign mart for implements of war; Why such impress of shipwrights, whose sore task Does not divide the Sunday from the week; What might be toward, that this sweaty haste Doth make the night joint-labourer with the day: Who is't that can inform me?

Plugins vs. Skins

var Plugin = {
   init:function () {
      twiki.AjaxRequest.setProperties("SEARCHRESULTS",
           {
              container:"searchResultsPluginContainer",
               url:"%PUBURL%/%SYSTEMWEB%/TWikiAjaxContribExamples/test_hamlet.html?"
            });
   },
   loadSearchResultsButton:function () {
      // For testing try to use the earlier defined container
      // if all is well, this should not succeed
      twiki.AjaxRequest.setProperties("SEARCHRESULTS",
           {
               container:"searchResultsPluginContainer"
            });
      twiki.AjaxRequest.load("SEARCHRESULTS");
   }
}
Plugin.init();


var Template = {
   init:function () {
      twiki.AjaxRequest.setProperties("SEARCHRESULTS",
           {
               container:"searchResultsTemplateContainer"
            });
      twiki.AjaxRequest.lockProperties("SEARCHRESULTS", "container");
   }
}
Template.init();


var myrules = {
   '#loadSearchResultsButton' : function(el) {
      el.onclick = function() {
         Plugin.loadSearchResultsButton();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo


Plugin container
Template container

Caching results

function writeContent () {
   twiki.AjaxRequest.load(
      "CACHEDRESULTS",
      {
         container:"cachedContentContainer",
         url:"%SCRIPTURL{view}%/%SYSTEMWEB%/WikiSyntaxSummary?skin=text",
         cache:true
      });
}

function clearCache () {
   twiki.AjaxRequest.clearCache("CACHEDRESULTS");
}

var myrules = {
   '#example_caching_demoshow' : function(el) {
      var oldOnClick = el.onclick;
      el.onclick = function() {
         writeContent();
         oldOnClick();
         return false;
      }
   },
   '#clearCacheButton' : function(el) {
      el.onclick = function() {
         clearCache();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo


Custom loading indicator

var indicatorHtml = "<div style=\"background-color:red; color:white; padding:.5em;\">Loading...<\/div>";

twiki.AjaxRequest.setProperties("CUSTOM_CONTAINER",
   {
      container:"customIndicatorContainer",
      url:"%PUBURL%/%SYSTEMWEB%/TWikiAjaxContribExamples/test_hamlet.html?",
      indicator:indicatorHtml
   });
            
function loadWithCustomIndicatorButton () {
   twiki.AjaxRequest.load("CUSTOM_CONTAINER");
}

var myrules = {
   '#loadWithCustomIndicatorButton' : function(el) {
      el.onclick = function() {
         loadWithCustomIndicatorButton();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo


HTML processing

twiki.AjaxRequest.setProperties(
   "HTML_DATA",
   {
      url:"%SCRIPTURL{view}%/%SYSTEMWEB%/WikiSyntaxSummary?skin=text",
      handler:"handleHtml",
      scope:this,
      container:"cachedHtmlProcessingContentContainer",
      cache:true
   });
   
function handleHtml (inId, inHtml) {

   // example 1: wrap in styled container
   var processedHtml = "<h2>Processed text:<\/h2>" + 
      "<div style=\"font-style:italic;\">" +
      inHtml +
      "<\/div>";
   var element = twiki.HTML.setHtmlOfElementWithId(inId, processedHtml);
      
   // example 2: style list elements
   var attributes = {
          "class":"twikiSmall twikiGrayText",
          "style":
             {
                "fontSize":"20px",
                "backgroundColor":"#444",
                "borderLeft":"5px solid red",
               "margin":"0 0 1em 0"
             }
       };
   twiki.HTML.setNodeAttributesInList(element.getElementsByTagName('ul'), attributes);
   
   // example 3: reverse texts
   reverseNodeTextsInList(element.getElementsByTagName('p'));

   // return HTML to be cached
   return twiki.HTML.getHtmlOfElementWithId(inId);
}

function reverseNodeTextsInList (inNodeList) {
   var i, ilen = inNodeList.length;
   for (i=0; i<ilen; ++i) {   
      var node = inNodeList[i];
      if (node && node.nodeType == 3) {
         node.data = reverseText(node.data);
      }
      if (node && node.nodeType == 1) {
         node.firstChild.data = reverseText(node.firstChild.data);
      }
   }
}

function reverseText (inText) {
   if (!inText) return '';
   var outText = "";
   var i, ilen = inText.length;
   for (i=0; i<ilen; ++i) {
      outText = inText.substring(i, i+1) + outText;
   }
   return outText;
}

function loadHtmlContent () {
   twiki.AjaxRequest.load("HTML_DATA");
}

function clearHtmlCache () {
   twiki.AjaxRequest.clearCache("HTML_DATA");
}

var myrules = {
   '#example_htmlProcessing_caching_demoshow' : function(el) {
      var oldOnClick = el.onclick;
      el.onclick = function() {
         loadHtmlContent();
         oldOnClick();
         return false;
      }
   },
   '#clearHtmlProcessingCacheButton' : function(el) {
      el.onclick = function() {
         clearHtmlCache();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo


XML data handling

twiki.AjaxRequest.setProperties(
   "COUNTRIES",
   {
      url:"%PUBURL%/%SYSTEMWEB%/TWikiAjaxContribExamples/test_cities.xml?",
      handler:"processCountryData",
      scope:this,
      type:"xml",
      container:"countriesContainer"
   });
   
function processCountryData (inContainerId, inXml) {
   var countries = [];
   var elems = inXml.getElementsByTagName("country");
   if (elems) {
      for (var i=0; i<elems.length; i++) {
         countries[i] = elems[i].getAttribute("name");
      }
      countries.sort();
   }
   var outText = "";
   var ilen = countries.length;
   if (ilen == 0) return;
   
   for (var i=0; i<ilen; ++i) {
      outText += "<li>" + countries[i] + "<\/li>"
   }
   outText = "<ul>" + outText + "<\/ul>";
   twiki.HTML.setHtmlOfElementWithId(inContainerId, outText);
}


function showCountries () {
   twiki.AjaxRequest.load("COUNTRIES");
}

var myrules = {
   '#loadXmlDataButton' : function(el) {
      el.onclick = function() {
         showCountries();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo


Countries

Sending data with POST

function postSearchForm () {
   var queryString = twiki.Form.formData2QueryString(
      document.getElementById('searchForm')
   );
   twiki.AjaxRequest.load(
      "SEARCH_DATA",
      {
         container:"searchResults",
         url:"%SCRIPTURLPATH{search}%/%INCLUDINGWEB%/%INCLUDINGTOPIC%",   
         method:"POST",
         postData:queryString
      });
}

var myrules = {
   '#submitSearchButton' : function(el) {
      el.onclick = function() {
         postSearchForm();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo

  Advanced search | Help
TIP: to search for all topics that contain "SOAP", "WSDL", a literal "web service", but not "shampoo", write: soap wsdl "web service" -shampoo
Search where:       
(otherwise search TWiki Web only)
Search results

Dealing with failure

twiki.AjaxRequest.setProperties(
   "FAILURE",
   {
      failHandler:"handleFailed",
      failScope:this
   });

function handleFailed(inName, inStatus) {
   var html = "<div style=\"background:#ffc; padding:.5em;\">" + 
      "Could not load contents. Please try again later." + 
      "<\/div>";
   twiki.HTML.setHtmlOfElementWithId("failureContainer", html);
}

function loadFailure () {
   twiki.AjaxRequest.load(
      "FAILURE",
      {
         container:"failureContainer",
         /* use wrong url */
         url:"%PUBURL%/%SYSTEMWEB%/twikiajaxcontrib/bla"
      });
}

var myrules = {
   '#failureButton' : function(el) {
      el.onclick = function() {
         loadFailure();
         return false;
      }
   }
};
Behaviour.register(myrules);

Demo


Topic attachments
I Attachment Action Size Date Who Comment
xmlxml test_cities.xml manage 46.0 K 02 Nov 2006 - 00:18 UnknownUser  
htmlhtml test_hamlet.html manage 241.2 K 29 Oct 2006 - 19:39 UnknownUser  
Topic revision: r2 - 02 Nov 2006 - 22:04:16 - TWikiContributor
 
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback
Note: Please contribute updates to this topic on TWiki.org at TWiki:TWiki.TWikiAjaxContribExamples