1 Simple Javascript examples

The code below shows some of the things that can be done with Javascript.
<a href='' onMouseOver='window.alert("You cannot!")'>try to click this</a>
<p>
<input type='button' 
       value='Click here for alert' 
       onClick='window.alert("Hello?")'/>
<p>
<input type='button' 
       value='Click here for confirmation' 
       onClick='temp=window.confirm("Would you like to confirm?");
                  window.status=(temp)?"true":"false"'/>
<p>
<input type='button' 
       value='Click here for prompt' 
       onClick='temp=window.prompt("Enter some text:","default value");
                  window.status=temp '/>
<p>
<a href='' 
   onMouseOver='window.status="Go on"; return true'
   onMouseOut='window.status="Finished"'>Watch the status bar</a>
<p>
<a href='javascript:history.back();'>back</a>
<a href='javascript:history.forward();'>forward</a>
<p>
<input type='button' 
       value='open new window'
       onClick='newwin=window.open("http://www.ostfalia.de","newwin",
                  "toolbar=no,scrollbars=yes,status=no,width=200,height=100"); '>
<input type='button' 
       value='close new window'
       onClick='newwin.close();' >
<p>
<script language="JavaScript">
  function square(i) {
    document.write("The function takes this ", i ,"<br>")
    return i * i
  }
  document.write("and calculates its square: ",square(5),".")
</script>

1.1 Exercise

1) Try the code. Click the buttons, move your mouse over the links and click the links. In some case the actitivity is shown in the status bar (window.status). Look through the code and make sure that you understand what it does.

1.2 More complex examples

The exercises below are fine when viewed via Firefox or Safari. If you use Internet Explorer, there seems to be problem with reloading the page.

The first example opens an XML file and reads its content. A sample xml file called "text.xml"

<?xml version="1.0" ?>
<maintag>
Here is some content.
</maintag>
is opened by the following script. The content of "maintag" is parsed using DOM and written into an alert box. The GetXmlHttpObject function is required because of differences between Internet Explorer and other browsers.
<html><head>
<script type='text/javascript'>
var request

function popupfile() {
  request=GetXmlHttpObject()
  if (request==null) {
    alert ("Browser does not support HTTP Request")
    return
  }
  request.open("GET","text.xml",true)
  request.send(null)
  request.onreadystatechange=stateChanged
}

function stateChanged() {
  if (request.readyState==4) {
    var xmldoc = request.responseXML;
    var root_node = xmldoc.getElementsByTagName('maintag').item(0);
    alert(root_node.firstChild.data);
  }
}

function GetXmlHttpObject() {
  var objXMLHttp=null
  if (window.XMLHttpRequest) {
    objXMLHttp=new XMLHttpRequest()
  } else if (window.ActiveXObject) {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
  return objXMLHttp
}
</script>
</head>
<body>
<input type='button' onclick="popupfile()" value='click here'/>
</body></html>
The following second example shows how to change text in a page without refreshing the page.
<html><head>
<script type='text/javascript'>
function rewriter(parameter,content){
  document.getElementById(parameter).innerHTML=content;
}
</script>
</head><body>

I would like some <span id="flavour">what kind of flavour</span> ice cream.

<p>
<input type='button' 
       onclick='rewriter("flavour","chocolate")' 
       value='chocolate'/>

<input type='button'
       onclick="javascript:document.getElementById('flavour').innerHTML='strawberry'"
       value='strawberry'/>
<p>
<a href=#
onclick="javascript:document.getElementById('flavour').innerHTML='peach'">
peach</a>

</body></html>

1.3 Exercise

2) Try both scripts and make sure that you understand how they work.

1.4 A first AJAX example

The two previous scripts can be combined in order to create an AJAX example. This AJAX script reads content from a file in the background and refreshes a page without reloading. The content is stored in a PHP file (which needs to reside in the PHP directory on a webserver). The following php file ("ajaxinput.php") is very simple and only contains three choices. In more advanced applications, this PHP file could contain more complex code, such as connecting to a database or interacting with other scripts.
<?php  switch($_REQUEST['action']) {
    case 'one':
      echo "chocolate";
      break;
    case 'two':
      echo "strawberry";
      break;
    default:
      echo "peach";
      break;
  }
?>
The function "rewriter()" is combined with the code from the function "popupfile()" above:
var request
var param 
  
function rewriter(parameter,content) {
  param = parameter 
  request=GetXmlHttpObject()
  if (request==null) {
    alert ("Browser does not support HTTP Request")
    return
    }
  request.open("GET", "ajaxinput.php?action="+content, true)
  request.send(null)
  request.onreadystatechange=stateChanged
}
The function "stateChanged()" now uses request.responseText instead of request.responseXML. It stores the response in the innerHTML instead of sending it to an alert box as before.
  if (request.readyState==4 || request.readyState=="complete") {
    javascript:document.getElementById(param).innerHTML = request.responseText;
    }
  }
The function "GetXmlHttpObject()" is unchanged. The body of the file contains three buttons for the different ice cream flavours. All three buttons use the rewriter function.

1.5 Exercise

3) Implement the AJAX script using the two files from exercise 2) following the instructions provided above.

4) Change the script from the previous exercise so that it reads the content from an XML file, which contains a tag for each flavour (<one>chocolate</one>, etc).