Yahoo! JavaScript Library and AjaxPro

Michael Schwarz on Friday, October 6, 2006

There are a lot of great JavaScript libraries available that are used be developers to add Ajax and Web 2.0 to their web sites. While AjaxPro [1] is optimized to run on all web browsers including Windows Mobile devices I got some requests on supporting the Yahoo! JavaScript libraries [2]. I have done some internal changes that will allow you do use the Yahoo! JavaScript files instead of the generated files from AjaxPro. Because there is no JSON parser in the Yahoo! lib I'm using the json.js written by Douglas Crockford [3]. But first have a look at the ASP.NET page (C#):

<pre>[AjaxPro.AjaxNamespace(<span class="str">&quot;Home&quot;</span>)]</pre><pre><span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> _Default : System.Web.UI.Page</pre><pre>{</pre><pre> [AjaxPro.AjaxMethod]</pre><pre> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> HelloWorld(<span class="kwrd">string</span> name)</pre><pre> {</pre><pre> <span class="kwrd">return</span> <span class="str">&quot;Hello &quot;</span> + name;</pre><pre> }</pre><pre> <span class="kwrd">protected</span> <span class="kwrd">void</span> Page_Load(<span class="kwrd">object</span> sender, EventArgs e)</pre><pre> {</pre><pre> <span class="rem">// AjaxPro.Utility.RegisterTypeForAjax(typeof(_Default));</span></pre><pre> }</pre><pre>}</pre> The only difference I do is removing the RegisterTypeForAjax call which will include the AjaxPro JavaScript files to the current page. Now, have a look at the client-side JavaScript source code:

<script type="text/javascript">

var callback = {
success: function(json) {
var o = json.parseJSON();
alert(o.result);
}
};

var args = {};
args.name = "Michael"; 

YAHOO.util.Connect.initHeader("x-ajaxpro-method", "HelloWorld"); 
var connectionObject = YAHOO.util.Connect.asyncRequest("POST",
"ajaxpro/_Default,App_Code.ashx", callback, args.toJSONString()); 

</script>

The first object callback is used to run an asyncronous XmlHttpRequest request. The sucsess function will be called when the requests is finished. Next we have the arguments we need for the .NET method HelloWorld. If you look in the C# source code above you will see the correct notation of the argument name:

var args = {};
args.name = "Michael"; 

To call an AjaxMethod AjaxPro is using a http header x-ajaxpro-method. In my example you have set this value to HelloWorld:

YAHOO.util.Connect.initHeader("x-ajaxpro-method", "HelloWorld"); 

Now, we can invoke the AjaxMethod using the YAHOO.util.Connect method. AjaxPro needs the arguments in the http body as a JSON string. For this I use the method toJSONString() which is included in the json.js from Douglas.

var connectionObject = YAHOO.util.Connect.asyncRequest("POST",
"ajaxpro/_Default,App_Code.ashx", callback, args.toJSONString()); 

I will publish a first beta during the weekend.