[ DWR Website | Web Application Index ]

# Dynamically Updating Text

This is a simple demonstration of updating a web-page with text fetched from JSON-RPC service provided by DWR.

It is similar to the plain DWR version of this demo. Using vanilla DWR is simpler and more powerful than using JSON-RPC, however JSON-RPC is useful when you need to use a different client.

- Demo
- How it works
- Source

Name:
Reply:

In this example we're using Dojo's JSON-RPC handler to call into DWR's JSON-RPC service, however we could use any JSON-RPC client. Dojo's API requires that we first register the call:

    var services = new dojox.rpc.Service({
        target:"../dwr/jsonrpc",
        transport:"POST",
        envelope:"JSON-RPC-1.0",
        contentType:"application/json",
        services:{
            "Demo.sayHello":{
                returns:{"type":"string"},
                parameters:[{"type":"string"}]
            }
        }
    });

When you click on the "Send" button the browser calls the onclick event, which calls the `update()` function:

    function update() {
        var name = dojo.byId("demoName").value;
        var deferred = services.Demo.sayHello(name);
        // ...
    }

deferred is a Dojo concept for something that will happen in the future. We need to add a callback to the deferred object:

    deferred.addCallback(function(result) {
        dojo.byId("demoReply").innerHTML = result;
    });

This is a good deal more complex than the plain DWR version, however using JSON-RPC allows interaction with systems that are not using a DWR client.

## HTML source:

    <p>
      Name:
      <input type="text" id="demoName"/>
      <input value="Send" type="button" onclick="update()"/>
      <br/>
      Reply: <span id="demoReply"></span>
    </p>

## Javascript source:

    var services = new dojox.rpc.Service({
        target:"../dwr/jsonrpc",
        transport:"POST",
        envelope:"JSON-RPC-1.0",
        contentType:"application/json",
        services:{
            "Demo.sayHello":{
                returns:{"type":"string"},
                parameters:[{"type":"string"}]
            }
        }
    });

    function update() {
        var name = dojo.byId("demoName").value;
        var deferred = services.Demo.sayHello(name);
        deferred.addCallback(function(result) {
            dojo.byId("demoReply").innerHTML = result;
        });
    }

## Java source:

    package org.getahead.dwrdemo.simpletext;

    public class Demo {
        public String sayHello(String name) {
            return "Hello, " + name;
        }
    }

## dwr.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE dwr PUBLIC
        "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
        "http://getahead.org/dwr/dwr20.dtd">

    <dwr>
      <allow>
        <create creator="new" javascript="Demo">
          <param name="class" value="org.getahead.dwrdemo.simpletext.Demo"/>
        </create>
      </allow>
    </dwr>