Simple Text Generation Demo

[ DWR Website | Web Application Index ]

# Dynamically Updating Text

This is a simple demonstration of how to dynamically update a web-page with text fetched from a web server.

- Demo
- How it works
- Source

Name:
Reply:

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

    function update() {
      var name = dwr.util.getValue("demoName");
      Demo.sayHello(name, loadinfo);
    }

`dwr.util.getValue()` is a utility to get the value of any element, in this case an input field, but it could be a div or a select box.

DWR is asynchronous due to the way Javascript works so it won't halt the web browser while we are waiting for the background HTTP request to return. So the parameter `loadinfo` names a function to be called when the call has returned.

On the server, DWR calls the `Demo.sayHello()` Java method:

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

When this method returns, DWR calls `loadinfo()` function which moves the text to the reply span:

    function loadinfo(data) {
      dwr.util.setValue("demoReply", data);
    }

`dwr.util.setValue()` is a utility that takes the data you pass in the second parameter and works out how to fit it to go into the HTML element specified by id in the first parameter. This function is one of several neat Javascript utilities that make working with DWR much easier.

We could simplify things by writing the 2 Javascript functions together like this:

    function update() {
      var name = dwr.util.getValue("demoName");
      Demo.sayHello(name, function(data) {
        dwr.util.setValue("demoReply", data);
      });
    }

And that's it. In effect we have written much less than 10 lines of code to get data from the server, and display it in the browser.

## 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:

    function update() {
      var name = dwr.util.getValue("demoName");
      Demo.sayHello(name, function(data) {
        dwr.util.setValue("demoReply", data);
      });
    }

## 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>