Home

Jul 8, 2007

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:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/CrmSdk3_0/htm/v3d0accessingwebservices.asp

Here's the code example of that page:
// Declare variables.
var i=0; var j=0; var k=0; var r=0;
var serverUrl =
http://www.webservicex.net/;

// This is the picklist.

switch (parseInt(event.srcElement.DataValue, 10))

{ case 1: i = "JPY"; break; case 2: i = "GBP"; break; case 3: i = "EUR"; break; }

// Instantiate at connection to the Web service and call the get method.

var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.open("get", serverUrl + "/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency="+escape(i), false);

xmlhttp.send();

var startTag = "";

var endTag = "
";

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;

No comments: