Accessing webservices via Javascript (aka AJAX)

Several times I've been asked, or saw the question on the newsgroups, how to create a piece of javascript code which retrieves data from a webservice. This information has been included in the SDK and you'll be able to find it here:

Here's the code example of that page:

// Declare variables.
var i=0; var j=0; var k=0; var r=0;
var serverUrl = "";

// This is the picklist.
switch (parseInt(event.srcElement.DataValue, 10))
case 1:
i = "JPY";
case 2:
i = "GBP";
case 3:
i = "EUR";

// Instantiate at connection to the Web service and call the get method.
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");"get", serverUrl + "/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency="+escape(i), false);
var startTag = "<double xmlns=\"http://www.webserviceX.NET/\">";
var endTag = "</double>";
var exch;
var valueStart = 0;
var valueEnd = 0;

// Parse the returned XML string.
valueStart = xmlhttp.responseXML.xml.indexOf(startTag, valueEnd) + startTag.length;

valueEnd = xmlhttp.responseXml.xml.indexOf(endTag, valueEnd+1);
exch = xmlhttp.responseXML.xml.substring(valueStart, valueEnd);

// Set the Exchange rate on the custom attribute.
crmForm.all.fabrikam_exchangerate.DataValue = parseFloat (exch);
j = crmForm.all.totalamount.DataValue;
var kk = j*(parseFloat(exch));

// Calculate and set the total sum in the selected currency.
crmForm.all.fabrikam_totalcurrency.DataValue = kk;


Anonymous said...

Hahaha ... lol :)

Well, does the SDK also provide a JS library which parses SOAP envelopes or XML-RPC's?

But good thinking putting this on your blog!

Anonymous said...

Thanks for providng this information. From last two days i am searching for calling the webservice method from javascript i thinking of using the remote calling but i think this one is nice. I dont kno weather it will execute or not. But thanks for giving that documentation site of MSDN. I hope i will come out of the problem soon. Thank you.

K Shiva Prakash.

Anonymous said...

Hello, Ronald!

I have tryed your piece of code, but modified it a little bit:"get", serverUrl + "/isv_extensions/opp_total.asmx/factTotal", false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("viewID=" + escape(crmGrid.GetParameter("viewid")));
result = String(xmlhttp.responseXML.selectSingleNode("/int").text);

It works fine if MSIE is running on the same machine where web server is (i.e. local).
But on all other computers xmlhttp.responseXML.xml returns empty string.
Do you have any clue why it does not work?

Kind Regards,
Sergey Slukin,

Ronald Lemmen said...


Does your webservice work from other machines if you call it in code?