benjii.me

jQax – A Simple jQuery Ajax Wrapper with Loading Notification

I dont think this is quite what I meantUPDATE: I've created a jQuery plugin version of this code which I've blogged about here!

Yeah, Yeah, What do I copy?

The full code is below:

REXML could not parse this XML/HTML: 
<pre class="prettyprint">// jQax.js - A wrapper for jQuery ajax functionality aimed at .NET services and page methods
// Ben Cull - 12 August 2010

function jQax() {

this.CallWebServiceWithGET = function (WebService, GetData, ShowLoading, LoaderText, SuccessCallBack, ErrorCallback) {

    if (ShowLoading)
        ShowLoader(LoaderText);

    if (WebService == "")
        return 1; // Incorrect Parameters

    if (ErrorCallback == null)
        ErrorCallback = jQax.DefaultErrorCallBack;

    if (typeof (GetData) === "object")
        GetData = $.param(GetData);

    $.ajax({
        type: "GET",
        url: WebService,
        data: GetData,
        success: SuccessCallBack,
        error: ErrorCallback
    });

    return 0; // Successful
}

this.CallWebServiceWithJSON = function (WebService, JsonData, ShowLoading, LoaderText, SuccessCallBack, ErrorCallback) {

    if (ShowLoading)
        ShowLoader(LoaderText);

    if (WebService == "")
        return 1; // Incorrect Parameters

    if (ErrorCallback == null)
        ErrorCallback = jQax.DefaultErrorCallBack;

    if (typeof(JsonData) === "object")
        JsonData = JSON.stringify(JsonData);

    $.ajax({
        type: "POST",
        url: WebService,
        data: JsonData,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: SuccessCallBack,
        error: ErrorCallback
    });

    return 0; // Successful
};

function ShowLoader(LoaderText) {
    var loadingText = "Loading...";
    if (LoaderText != null &amp;&amp; LoaderText != "") {
        loadingText = LoaderText;
    }

    $("#divLoader").text(loadingText);
    $("#divLoader").fadeIn("fast");
}

this.DefaultErrorCallBack = function (XMLHttpRequest, textStatus, errorThrown) {
    var response = eval("(" + XMLHttpRequest.responseText + ")");
    var output = "Message: " + response.Message + "\n\n";
    output += "StackTrace: " + response.StackTrace;
    alert(output);
}

$(document).ready(function () {

    $("#divLoader").ajaxStop(function () {
        $(this).stop(true, true).fadeOut("fast");
    });

});

};

jQax = new jQax();</pre>

That’s all well and good, but how do I use it?

Well Its quite simple, if you have a page method or web service you call It like so (the call using the GET method is much the same):
REXML could not parse this XML/HTML: 
<pre class="prettyprint">jQax.CallWebServiceWithJSON(
    "MyPage.aspx/MyMethod",
    {
        parameterName: "parameterValue",
        horses: 40
    },  // can be any javascript object (if json2.js is enabled), otherwise you must pass in a json string
    true, // shows the divLoader
    "Custom Text for Loader...", // use null for default
    function(data, eventArgs) { // This is called on success
        // data is exactly whats returned by the server
        // quick and easy JSON parsing can be done like so:

    var result = $.parseJSON(data);

    // Deal with result here
});</pre>
To enable automatic JSON serialization you must download the following and add it to your head section:json2.js from http://www.json.org/json2.js

Page Methods must be setup like this!

If you want to use page methods with your fancy new ajax wrapper, you need to ensure the following two things:

  • Your page methods are static
  • Your page methods are decorated with the [WebMethod] attribute, found in the System.Web.Services namespace
Like so:
REXML could not parse this XML/HTML: 
<pre class="prettyprint">[WebMethod]
public static string MyMethod(string parameterName, string horses)
{
    // Keep in mind, everything comes in and goes out as a string

return parameterName + horses;

}</pre>

If you need more help…

Here are some links to help you out with some more complex uses of the above code: