Hooking up wwJSONService

It's easiest to see how this class works to see the server side implementation in a Process method. You can simply set up a process method like this:
FUNCTION JsonCallbacks *** You'll need to let the object know which method to call *** when using plain JSON callbacks (ie. not using wwAjaxMethodCallback) lcMethod = Request.QueryString("Method") && ie. HelloWorld *** Instantiate or reference the class that will will handle the method call *** Here I just use the Process class itself which will lhandle the call loTarget= THIS *** Instanantiate the service loService = CREATEOBJECT("wwJsonService") *** Return a JSON Response Response.ContentType = "application/x-javascript" *** Write out the result from CallMethod which returns the JSON for the method *** or a JSON Error object if the call failed Response.Write( loService.CallMethod(Request,loTarget,lcMethod) ) RETURN *** This is the target process method PROTECTED FUNCTION HelloWorld(lcName) RETURN "Hello " + lcName + ". Time is: " + Time()

To call this service from client script make sure you include wwScriptLibrary.js into the page and then call:

<script type="text/javascript"> function Test() { ajaxJson("jsoncallbacks.wwd?Method=Helloworld", "Rick Strahl",TestIt_Callback,OnError); } function TestIt_Callback(result) { alert(result); // shows: Hello Rick. Time is ... } function OnError(error) { alert("Error: " + error.message); } </script>

Note that using the client side ajaxJson() function allows you to pass exactly one parameter to the server (use null for none) and you need to make sure you method accepts one parameter. If you need to pass more than one parameter you can pass an object that holds the parameters. For example in JavaScript you can declare:

var parms = { Name: "Rick", Rate: 150.00 }; ajaxJson("jsoncallbacks.wwd?Method=Helloworld", parms,TestIt_Callback,OnError);

and you can then pass this parameter. The server code will then receive the object as a parameter and can extract the individual parameters. Objects can be nested as well. Your result is the result from the method call on the server encoded in JSON format. You can return simple values, objects, hierarchical objects and even cursors (return "cursor:CursorName").

You don't have to use the Web Connection client code either - it's possible to use other libraries to access this functionality - you can use GET operations or POST operations and simply passing data via query strings or POST data. For example, to use jQuery to call the same code above:

jQuery.ajax( { url: "jsoncallbacks.wwd?Method=Helloworld", dataType: "json", success: TestIt_Callback, error: OnError } );

This works just as well, although you loose the capability to pass parameters (unless you POST and JSON encode them on your own). jQuery.ajax for example allows you to serialize form fields automatically and send that along with the request. To pass JSON parameters with jQuery you'll need to use a JSON serializer

The point though is that you can call into a JSON service configured many different ways and it doesn't have to be from Web Connection client script code.

However, using the wwScriptLibrary is the easiest way by far as it allows passing data as real types and directly returning a JSON response. If you want even more control over the process you can use the full featured wwAjaxMethodCallback class which allows you to explicitly define what parameters to pass to the method and what additional form data to send to the server in addition to the parameters.

Here's another example of the service implementation on the server - this time using a separate object to handle the callbacks:

FUNCTION JsonCallback *** Class that holds methods to call - could also be THIS (current Process class) loTarget= CREATEOBJECT("targetclass") *** Create the Service object loService = CREATEOBJECT("wwJsonService") *** We'll always return an JavaScript/JSON result Response.ContentType = "application/x-javascript" *** Call the method - it will pick up parameters out of the request object Response.Write( loService.CallMethod(Request,loTarget) ) RETURN ... *** External class that holds methods to be called *** Methods are simply plain methods that take string inputs (!!!) *** and return any kind of result which is turned into JSON DEFINE CLASS TargetClass as Custom FUNCTION HelloWorld(Name) RETURN "Hello " + name + " " + Time() FUNCTION GetServerDate() RETURN DateTime() FUNCTION ReturnObject() loObj = CREATEOBJECT("EMPTY") ADDPROPERTY(loObj,"CurrentTime",DateTime()) ADDPROPERTY(loObj,"VfpVersion",Version()) RETURN loObj FUNCTION GetCursor() select * from tt_cust order by company into cursor TQuery return "alias:Tquery" ENDDEFINE

Once this JsonCallback method is hooked up you can call methods on the TargetClass from the client with the following code:

function ManualMethodCall() { // *** Example how to manually make a remove method call without the // *** built in proxy. This allows dynamic method invokation. // *** Create the callback class and pass the ID of the Callback control var Manual = new AjaxMethodCallback("Callback"); // *** serverUrl points at our Process method Manual.serverUrl = "JsonCallback.wwd"; // *** You can specify how data is posted back. Get, Post, PostNoViewState and parameters only (default) Manual.postbackMode = "PostMethodParametersOnly"; // *** Call method: Method name, Array of parameters, Callback and Error handlers Manual.callMethod("HelloWorld",[$("txtName").value],ManualMethodCall_Callback,OnPageError); } function ManualMethodCall_Callback(Result) { alert("*** Server Response:\r\n" + Result); } function OnPageError(Exception) { alert("*** Error occurred in callback: " + Exception.message); }

You'll also need to include the wwScriptLibrary at the top of your document (which installs by default in the images directory with a new project):

<script src="images/wwscriptlibrary.js" type="text/javascript"></script>

or you can use the more convenient WebResource Url with any supported scriptmap:

<script src="WebResource.wwd?Resource=wwscriptlibrary" type="text/javascript"></script>

The advantage of the latter is that you don't have to worry about versioning as this version of the library is embedded from the current Web Connection version. The library is also automatically GZip compressed.

Even easier: Using the MethodCallback Server Control

By far the easiest way however is to use a Web Control Framework Page and the wwAjaxMethodCallback control. This control allows you to drag and drop the control onto a form and set all configuration options on the control with a few clicks. You then simply implement the callMethod call on the client. The wwAjaxMethodCallback control can also handle automatic routing back to the current page so you don't even have to declare the JSON serializer. You can simply implement a method on the Page and it will be called directly. Alternately you can assign a target object to handle the callbacks instead as above.


See also

Class wwJsonSerializer | Ajax Utility Functions |


  Last Updated: 10/3/2008 | © West Wind Technologies, 2008