Calling the JSON Service with AJAX

A wwCallbackHandler derived service is essentially a REST endpoint and you can call it in a number of different ways:


These examples all use wwScriptLibrary, but that's purely optional. You can use any AJAX library that you like for any of the mechanisms although the first option is probably useful only if you use wwMethodCallback.

Use with jQuery

The following is an example of using jQuery to call a handler:

Passing a raw POST buffer:

$.ajax( { url: "ClientCallbacks.ashx?Method=CallbackWithPost", data: { Name: "Rick", Date: new Date(), Value: 20 }, processData: true, // turn input into querystring style values dataType: "json", // result data type type: "POST", success: function(result) { alert("Message from Server:\r\n" + result.toLocaleString() ); }, error: function( xhr, message, ex) { alert("Ajax Error: " + message); } } );

This code uses an object that is parsed by jQuery.ajax into a raw POST buffer (processData=true which converts a map into POST variables).

Passing a JSON string (note the data must be a JSON string not an object/map!):

// *** Object to serialize var person = {Name:"Rick",Address:"32 Kaiea",Entered: new Date()}; // *** use wwScriptLibrary's embedded JSON based on Crockford's with mods // *** you can use whatever mechanism you choose to generate JSON however // *** although we recommend you use wwScriptLibrary because it's most compatible // *** with what the server expects. var jsonData = JSON.serialize( person ); $.ajax( { url: "ClientCallbacks.ashx?Method=TestDate", contentType: "application/json", data: jsonData, processData: false, // treat as json dataType: "json", type: "POST", success: function(result) { alert("Message from Server:\r\n" + result.toLocaleString() ); }, error: function( xhr, message, ex) { alert("Ajax Error: " + message); } } );

In this code the data sent is a JSON string. Here I use wwScriptLibrary and its JSON.serialize() function to convert and object into a JSON string that is then passed as a parameter, but you can use whatever mechanism or library you choose to arrive at a JSON string.




  Last Updated: 12/29/2007 | © West Wind Technologies, 2008