DOAP - Remote Abstract Data Access Protocol by Dave

<< IntroductionContentsParameters >>

First Simple Example: Hello World

As explained in the introduction DOAP has two components - the server (server-side PHP) and the client (client-side JavaScript).

This first simple example shows how we can call a function on the server and return the string "Hello World!" to be displayed on the client.

Click here to see this example run

Here is the commented source code for this example.

Server-Side DOAP Server PHP
<?php
ob_start(); // ensure no messy output from includes
 
// Our Hello World Function - just returns a string
function hello_world()
{
	return "Hello World!";
}
 
require("xmlcreate.inc.php"); // include the xmlCreate library
require("doap.inc.php"); // include the DOAP Server library
 
$doap = new DOAP_Server(); // create a DOAP Server object
 
$doap->Register("hello_world",0,0); // register the hello_world() function
 
ob_clean(); // clean any messy output from includes
 
$doap->Process(); // get DOAP Server to process the request
?>

The server side-code simply has a function called hello_world() that returns a string. DOAP is initialised, the hello_world() function is registered and then DOAP is called to process the request.

Client-Side DOAP Server HTML/JavaScript
<HTML>
<HEAD>
<TITLE>DOAP Example 1: Hello World</TITLE>
<!-- Include the DOAP Client JavaScript -->
<SCRIPT TYPE="text/javascript" SRC="doap.js"></SCRIPT>
 
<SCRIPT TYPE="text/javascript">
var doap = new DOAP(); // create the DOAP Client object
doap.url = "example1.php"; // set the DOAP Server URL
 
function hello_world() // this will call hello_world() on the DOAP Server
{
	try
	{
		var result = doap.call('hello_world'); // call hello_world() on server
	}
	catch(e) // catch any errors
	{
		// deal with any errors if it's a DOAP error or any other type of exception
		if(e instanceof DOAP_Error) alert("DOAP Error "+e.code+": "+e.desc);
		else alert("Unknown Error: "+e);
		return; // and exit the function if an error was encountered
	}
	// otherwise put the result into the results DIV
	document.getElementById('results').innerHTML = result;
}
</SCRIPT>
</HEAD>
 
<BODY>
<DIV ID="results" CLASS="result_div">Results will appear here BY MAGIC!</DIV>
<BR /><BR />
 
<!-- Now we have a link which will call the JavaScript function hello_world which
     in turn calls the hello_world() function on the server and outputs the result
     to the results div -->
<A HREF="#" onClick="hello_world();">Click me to execute hello_world()</A><BR /><BR />
 
<!-- And a link to clean the results div back if needed -->
<A HREF="#" onClick="document.getElementById('results').innerHTML='<BR />';">Clear Results DIV</A>
 
</HTML>
 

The client includes the DOAP JS, makes a DOAP object and defines a function that calls it (wrapped in try to catch any thrown errors). The function is called from the onClick event of an A HREF link.

<< IntroductionContentsParameters >>