Using XML and AJAX with Epoch Prime

Follow this step-by-step Guide to set up Epoch Prime on your server.

For the detailed Epoch Prime XML specification and guide, see the Epoch Prime XML specs page. For a detailed walkthrough of adding and removing dates, see the Dates in Epoch Prime page.

You Will Need

  1. Basic Knowledge of XML
  2. The Epoch Prime .js and .css files
  3. The ability to insert code into your page's <HEAD> or <BODY> sections.

Step 1. Embedding the XML data in your web page

XML, with its easy learning curve and flexibility, is quickly becoming the standard for sending data via the Web. Programming methods such as AJAX/AFLAX/etc all use XML to return data to the user's browser, and XML is the data format of choice for many inter-server operations. Currently the best way to embed XML in your pages is by placing it inside a JavaScript string constant (see below). For more (not necessarily recommended) methods, click here.

XML as a JavaScript String (Preferred)

Placing your XML into a JavaScript string is both standards-compliant and requires no special knowledge. It also makes it easier to pass the data in the string to Epoch Prime for initialization. This method works across all major browsers and is therefore the recommended method for embedding XML data in your web page.

<head>
<title>My page</title>
...
...
<script type="text/javascript">
var myxml = '<?xml version="1.0" encoding="UTF-8"?> <!--PHP users watch out for this line-->
 <mydata>
  <data name="firstitem">some data</data>
  <data name="seconditem">some other data</data> 
 </mydata>';
</script>
</head>'

Important: In order to avoid any "unterminated string literal/constant" errors, you must not have any line breaks in the XML string – the example above is formatted for easy reading.

Standards junkies may want to put a "\" before the "/" in every tag (i.e. "<\/data>" instead of "</data>") to ensure full standards compliance. The major browsers will work with it either way.

Step 2. Initializing Epoch Prime with the XML

Once you have an XML string, it's easy to load it into Epoch Prime.

Simply pass the XML string (or XMLDoc object, if already parsed) to Epoch Prime when you initialize the calendar and/or web page.

<head>
<title>Using XML to initialize Epoch Prime</title>
<link rel="stylesheet" type="text/css" href="[path_to_css]/epochprime_styles.js"/>
<script type="text/javascript" src="[path_to_javascript]/epochprime_classes.js">
<script type="text/javascript">
 /*The XML below can be hard-coded into the page by you,
  or generated by your server-side scripts (PHP, ASP, etc.)*/
 var myxml = '<mydata><datum1>value1</datum1><datum2>value2</datum2></mydata>';
 var mycalendar;
 window.onload = function() {
 //and initialize the calendar using the XML
 mycalendar = new EpochPrime(document.getElementById('container'),myxml);
};
</script>
</head>

For more on Epoch Prime's initialization, see the Epoch Prime Constructor Reference.

Step 3. Using XML After Epoch Prime is Initialized

After the page is loaded, You can use AJAX to update the dates and/or configuration of Epoch Prime. To do this, you'll need to send a request to the server, using the XMLHttpRequest object. Once you've obtained an XML response from the server, you may pass responseXML or responseText to Epoch Prime's importXML() function. The calendar will then update its configuration and dates to the XML data's specifications.

<script type="text/javascript">
 /*here getrooms.php will presumably return the available rooms for January 2006*/
 var url = 'http://www.mysite.com/ajax/getrooms.php?month=01&year=2006';
 /*we load the data into Epoch Prime via the onreadystatechange event handler*/
 myXMLHttp.onreadystatechange = function () {
  if(myXMLHttp.readyState == 4){
   mycalendar.importXML(myXMLHttp.responseXML);
  }
 };
 myXMLHttp.open('GET',url,true);
 myXMLHttp.send(null);
</script>

Saving the State of Epoch Prime with AJAX

One of the most difficult problems encountered when using AJAX involves saving the state of a page after the user changes it. Epoch Prime introduces the outputAjaxQueryString() and exportXML() methods— condensing the Epoch Prime's current state into a single encoded HTTP URL string or XML string. You can then send the data server-side using your AJAX framework, or directly using the XMLHttpRequest object.

Save data using outputAjaxQueryString():

outputAjaxQueryString() is useful for sending simple calendar data, such as the currently selected date(s), to the server. It will create a URL-encoded string containing all the currently selected dates in the calendar, as well as calendar state variables such as displayYear and displayMonth—if the includeConfig argument is true. See the outputAjaxQueryString() Documentation for more details.

<input type="button" value="Save Changes" onclick="saveChanges();"/>
...
...
...
<script type="text/javascript">
//sending data using outputAjaxQueryString():
function saveChanges() {
var url = 'http://www.example.com/processdata.php';
/*use outputAjaxQueryString() to output a URL-encoded string to send to the server for processing*/
var calendarData = mycalendar.outputAjaxQueryString('dates','Y-m-d',false);
myrequest.open('POST',url,true);
myrequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded charset=UTF-8');
myrequest.send(calendarData);

}
</script>
...
...
...

Save data using exportXML()

<input type="button" value="Save Changes" onclick="saveChanges();"/>
...
...
...
<script type="text/javascript">
function saveChanges() {
var url = 'http://www.example.com/processdata.php';
/*use exportXML() to output an XML string to send to the server for processing*/
var calendarData = 'cal_xml=' +encodeURIComponent(mycalendar.exportXML());
myrequest.open('POST',url,true);
myrequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded charset=UTF-8');
myrequest.send(calendarData);

}
</script>
...
...
...

Example Code and Demo

Below is a fully-functioning demo of using XML with Epoch Prime. Try out the demo by changing the configuration, date types, and selecting different dates. When you're ready, you can paste the code below into an empty HTML file and gain some insight on integrating Epoch Prime into your site.

Demo

XML code used

…And the Result:

The calendar dates and configuration are updated real-time whenever you call importXML(). The XML format is the same whether you are passing it on page/calendar initialization, or by user actions after the page has loaded (via importXML()).


Example Code

Here is some working example code you can use to paste into an empty HTML document. Don't forget to download the Epoch Prime Files and set the paths in the <script> and <link> tags in your new HTML file. This demo is written in XHTML, but will also work with the HTML doctypes.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Epoch Prime AJAX - XML Import Test Page</title>
<link rel="stylesheet" type="text/css" href="[path_to_css]/epochprime_styles.css"/>
<script type="text/javascript" charset="utf8" src="[path_to_javascript]/epochprime_classes.js"></script>
<script type="text/javascript">
var mycalendar, container; //declare calendar and container as global variables
window.onload = function() {
 //initialize the container
 container = document.getElementById('cal_container');
 /*xmldata can be static XML, or you can use a server-side language like PHP or ASP
   to print out the XML data between the quotes.
   Standards junkies may want to place a '\' in front of every closing tag, i.e.
   '<\/date>' instead of '</date>'
  IMPORTANT: the line breaks in the XML below are for presentation only.
  String constants in JavaScript must not have any hard line breaks or you will get an error!*/
 var xmldata = '<?xml version="1.0" encoding="UTF-8"?>
<importdata>
 <configs>
  <initcfg>
   <multiselect>yes</multiselect>
   <mode>flat</mode>
   <showweeks>yes</showweeks>
  </initcfg>
  <statecfg>
   <displayyearinitial>2006</displayyearinitial>
   <displaymonthinitial>7</displaymonthinitial>
   <displayyear>2006</displayyear>
   <displaymonth>7</displaymonth>
   <mindate>2005-09-11</mindate>
   <maxdate>2009-08-16</maxdate>
  </statecfg>
 </configs>
 <datesadd>
  <date type="normal" title="test" value="2006-07-24" selected="disabled"></date>
  <date type="holiday" value="2006-07-04" selected="yes"></date>
  <date type="normal" value="2006-07-13"></date>
  <date type="normal" value="2006-07-21"></date>
  <date type="normal" value="2006-07-29"></date>
 </datesadd>
</importdata>';
/*you can leave xmldata blank - if so, Epoch Prime will return to its default settings in calConfig()*/
 mycalendar = new EpochPrime(container,xmldata);
};
</script>
</head>
<body>
<h1>Epoch Prime AJAX test page for XML import</h1>
<p>If the XML importation works, you will see several dates highlighted in the calendar below:</p>
<div id="cal_container"></div> <!--where Epoch Prime will appear-->
...
...
</body>
</html>

Other Methods of Embedding XML in your page

Despite the growing populatity of XML, the W3C and major browsers have yet to come up with a deployable standard for embedding XML into web pages. As a result, some browsers have proprietary methods of embedding XML (see XML Data Islands in Internet Explorer). Here are 2 other ways to embed XML into your web page.

Placing XML directly inside your page content

Because most browsers ignore tags they do not recognize, it is possible to simply embed the XML directly in the page content. You can do this by creating a hidden <div> element and placing the XML inside it.

<body>
<h1>My page</h1>
...
...
<div id="embeddedxml" style="display:none;">
<?xml version="1.0" encoding="UTF-8"?> <!--PHP users watch out for this line-->
 <mydata>
  <data name="firstitem">some data</data>
  <data name="seconditem">some other data</data> 
 </mydata>
</div>
...
...
</body>

You can then access the XML data by accessing the <div> element's innerHTML JavaScript property:

<script type="text/javascript">
 //get the XML from the <div> element
 var myxml = document.getElementById('embeddedxml').innerHTML;
 //and initialize the calendar using the XML
 mycalendar = new EpochPrime(document.getElementById('container'),myxml);
</script>

The problem with this method is its complete lack of standards-compliance. While the major browsers can handle this method without problems, future versions may have stricter markup rules. We therefore recommend you do not use this method unless you absolutely have to.

XML Data Islands (Internet Explorer Only)

Internet Explorer introduces XML data islands as a way of embedding XML into page content. While useful, this method is not standards-compliant, and will not work for users running other browsers. You also need to be reasonably-familiar with XML data islands to implement this. Only implement this solution if you're sure your users run only Internet Explorer.

<body>
<h1>My page</h1>
...
...
<xml id="embeddedxml">
<?xml version="1.0" encoding="UTF-8"?> <!--PHP users watch out for this line-->
 <mydata>
  <data name="firstitem">some data</data>
  <data name="seconditem">some other data</data> 
 </mydata>
</xml>
</body>