Archive for June, 2009

Example using jQuery with ASP.Net (SOAP) WebServices

I don’t know about you, but I’ve had enough of slow loading aspx pages because of the huge ScriptManager JavaScript files that are needed to be downloaded. I also don’t see why I should have to register web services through it to be able to use them in my client side code.

Once answer is to use jQuery. We can access Asp.Net web services (SOAP) removing the need for the ScriptManager on your aspx page.

Asp.Net web services either use SOAP or JSON and for this post I will show you how to access your webservice using SOAP.

This is how you can do it:

First of all I like to organise all my JavaScript in to namespaces so that it stays neat so I declare the DT object.

var DT = {}

Then because we will be using Soap I have created a useful Soap function called getEnvelope which saves having to add the envelope xml each time you want to build a request.

DT.Soap = {
  getEnvelope: function(body) {
    var soapEnv =
    "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
        <soapenv:Body> \
           " + body + " \
        </soapenv:Body> \
     </soapenv:Envelope>";
    return soapEnv;
  }
}

You can use this ws object each time you define a new webservice.

DT.ws = function(wsUrl) {
    this.wsUrl = wsUrl;
}
DT.ws.prototype = {
    wsUrl: null,
    getData: function(soapEnvelope, fnComplete, fnSuccess, fnError) {
        $.ajax({
            url: this.wsUrl,
            type: "POST",
            dataType: "xml",
            data: soapEnvelope,
            contentType: "text/xml; charset=\"utf-8\"",
            complete: fnComplete,
            success: fnSuccess,
            error: fnError
        });
    }
}

Defining a new web service would then look something like the code below. We first create a new ws object instance and then define the HelloWorld method.

DT.wsCustom = new DT.ws("wsCustom.asmx");
DT.wsCustom.HelloWorld = function(fnComplete, fnSuccess, fnError) {
    var soapEnv = DT.Soap.getEnvelope("<HelloWorld xmlns='http://yournamespace.com/'></HelloWorld>");
    this.getData(soapEnv, fnComplete, fnSuccess, fnError);
}

Finally you can use your new web service with the following code.

DT.wsCustom.HelloWorld(function(xData,textStatus){
    alert("This is the xml response: " + xData.responseXML);
});

This is just a quick start to using jQuery to access Asp.Net web services. Here is part 2 to include XSL transforms and more advanced web methods.

Hope this helps.