At this point I am a JavaScript newbie, I have assiduously avoided a full fledged dive into the language until recently. That is difficult to believe as at least 50% of my job involves ASP.NET. However, the introduction of some really cool libraries has forced me into a desperate game of catch up.

One of my recent tasks was to try calling a web service from Javascript using Visual Studio 2005 and the obvious solution involves the use of XMLHttpRequest. The following sample solution covers a HTTP POST while passing a couple of simple parameters.

var oReq = getXMLHttpRequest(); 

if (oReq != null) {
    oReq.open("POST", "http://localhost/mydemo.asmx", true);
    oReq.onreadystatechange = handler; //call back function defined below
    oReq.send(“param1=22&name=Michael";);
}
else {
    window.alert("AJAX (XMLHTTP) not supported.");
} 

function getXMLHttpRequest() 
{
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            return null;
        }
    }
} 

//called when the service returns
function handler()
{
    if (oReq.readyState == 4 /* complete */) {
        if (oReq.status == 200) {
            alert(oReq.responseText);
        }
    }
}

This works great but I wanted to look at sending more complex data structures (which for java scripts generally refers to arrays) in a really intuitive way. This sounded simple but I started to run into weird things when trying to send anything but regulars vars. I did happen upon a really intuitive JavaScript library created by Mateo Casati, called SoapClient. It provides great support for all the types of arrays and even classes, the only real limitation in what you can send is JavaScript itself.

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

var url = "http://localhost/mydemo.asmx");

function handler(r)
{
    alert(r);
}

function MyNewSample() {
    var list = "This is a test";
    
    var pl = new SOAPClientParameters();
    pl.add("list", list);
    SOAPClient.invoke(url, "MyNewSample", pl, true, handler);
}

This option became almost immediately obsolete once I was given permission to use Visual Studio 2008 for the project. In VS2008 I am able to take advantage of the ScriptManager (as well as break points in JavaScript). This inferred upon me all the intellisense support for my web service that I would need for rapid development. It simply requires that you place the following script inside a form tag.

<asp:ScriptManager runat="server" ID="scriptManager">
    <Services>
        <asp:ServiceReference path="mydemo.asmx" />
    </Services>
</asp:ScriptManager>

image

 



Comment Section

Comments are closed.