Announcement: You can find the guides for Commerce 7.5 and later on the new Elastic Path Documentation site. The Developer Center continues to support Commerce 6.13.0 through 7.4.1.Visit new site

How to invoke server-side methods from JavaScript

How to invoke server-side methods from JavaScript

Web pages and templates that invoke server-side methods on a Javascript proxy must make the following declarations.

<!-- Reference the javascript proxy for the server-side object whose method is to be
invoked. Include a line such as the one below for each Java class where methods will
be invoked. -->
<script type='text/javascript' src='dwr/interface/customerService.js'></script>

<!-- Reference the dynamic JavaScript proxy generation library (engine.js) -->
<script type='text/javascript' src='dwr/engine.js'></script>

<!-- Reference the DWR utility library (util.js) -->
<script type='text/javascript' src='dwr/util.js'></script>

Note that these .js files are generated automatically by the DWR servlet. You do not need to create the customerService.js. It is a proxy for the customerService.

Once the above references are declared, server-side calls can be made by simply invoking methods on the Javascript proxy. The last parameter to the server-side method declares the Javascript callback method that will be invoked when the call returns from the server such as in the following example.

customerService.get(customerId, this.getCustomerCallback);

If an error handler is needed to perform additional logic on the browser side in the event that the call fails, use the following syntax.

customerService.update(customerToCommit,
       {callback:this.onCustomerCommitCallBack,
        timeout:5000,
        errorHandler:this.onCustomerCommitErrorHandler});

In the above example, a Javascript call metadata object is the last parameter to the remote method call. This object specifies both the call back method and the method that should be invoked in the event that the remote operation fails.

All callback methods have only one parameter, which is the return value from the remote method. A Javascript closure is needed to pass additional information.

shippingRegionService.list({callback:function(results) {
        message = function () {};
        if (results != null && typeof results == 'object') {
            message.data = results;
            if (source == "fromRegionSummaryPane") {
                dojo.event.topic.publish("onShippingRegionListReturnToSummary",
                  message);
            } else if (source == "fromServiceLevelDetailPane") {
              dojo.event.topic.publish("onShippingRegionListReturnToService",
                  message);
            }
        }
    }
});