Release 2.x‎ > ‎Development‎ > ‎

Javascript: xmlhttprequest

Introduction

This page demonstrates several examples of using the OpenPTK RESTful interface with the javascript and xmlhttprequest. The examples below show how to use the HTTP Accept header to request each of the 4 representation outputs supported (JSON, XML, HTML, and text), and display the results.

Test html page with javascript examples operations

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>OpenPTK xmlhttprequest tests</title>
   </head>
   <body>
      <h1>XMLHttpRequest Javascript Example</h1>


      <FORM>
         <INPUT TYPE="button" VALUE="Contexts"
                onClick="showHttpResource('contexts', 'contexts')">
         <INPUT TYPE="button" VALUE="Person-MySQL-JDBC"
                onClick="showHttpResource('context', 'contexts/Person-MySQL-JDBC')">
         <INPUT TYPE="button" VALUE="Person-MySQL-JDBC Subjects"
                onClick="showHttpResource('subjects', 'contexts/Person-MySQL-JDBC/subjects')">
         <INPUT TYPE="button" VALUE="Person-MySQL-JDBC Subjects"
                onClick="showHttpResource('subject', 'contexts/Person-MySQL-JDBC/subjects/jbauer')">
      </FORM>

   </body>
</html>



<script type="text/javascript">
   function showHttpResource(resourcetype, resource) {
      var url = '/openptk/resources/' + resource;

      // Create xmlhttprequest object
      var xmlhttp = null;
      if (window.XMLHttpRequest) {
         xmlhttp = new XMLHttpRequest();
         //make sure that Browser supports overrideMimeType
         if ( typeof xmlhttp.overrideContentType != 'undefined') { xmlhttp.overrideMimeType('text/xml'); }
      } else if (window.ActiveXObject) {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }  else {
         alert('Perhaps your browser does not support xmlhttprequests?');
      }

      // Create an HTTP GET request
      xmlhttp.open('GET', url, true);
      xmlhttp.setRequestHeader("Accept","application/json");

      // Set the callback function
      xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // Output the results
            alert(xmlhttp.responseText);
         } else {
            // waiting for the call to complete
         }
      };

      // Make the actual request
      xmlhttp.send(null);
   }
</script>