XQuery/Employee Search

From Wikibooks, open books for an open world
Jump to: navigation, search

This example shows JavaScript and XQuery combining to provide a directly updated Web page. AJAX is used in a form sometimes referred to as AHAH in which the server-side XQuery script returns an XHTML node (in this case a table containing the information about an employee) which is updated into the DOM using innerHTML.

The behavior of this application is explained in this interactive sequence diagram.

The search page[edit]

<html xmlns="http://www.w3.org/1999/xhtml" >
     <title>Emp query using AJAX</title>
      <script language="javascript" src="ajaxemp.js"/>
      th {{background-color:yellow}}
    <h1>Emp query using AJAX</h1>
    <form action="javascript:getEmp();">
      <label for="EmpNo"  title="e.g. 7369, 7499 and 7521."> Employee Number</label>
      <input type="text" size="5" name="empNo" id="empNo" />
      <input type="submit" value="Find"/> 
   <div id="emp"/>


The JavaScript script[edit]

function updateEmp() {
  if (http.readyState == 4) {
      var divlist = document.getElementById('emp');
      divlist.innerHTML = http.responseText;
      isWorking = false;

function getEmp() {
  if (!isWorking && http) {
    var empNo = document.getElementById("empNo").value;
    http.open("GET", "getemp.xq?empNo=" + empNo, true);
    http.onreadystatechange = updateEmp;  
    isWorking = true;

function getHTTPObject() {
  var xmlhttp;
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
  return xmlhttp;

var http = getHTTPObject(); //  create the HTTP Object
var isWorking = false;

The get script[edit]

declare function local:element-to-table($element) {
      {for $node in $element/*
                   { $node/text()   }
let $empNo := request:get-parameter("empNo",())
let $emp := //Emp[EmpNo=$empNo]
    if (exists($emp))
    then local:element-to-table($emp)
       <p>Employee Number {$empNo} not found.</p>

Get the XHTML fragment