Monday, December 18, 2006

How to consume UrbanDictionary service with Java Script

From my last entry, I had wrote that my instructor assign a project on mashing-up three web services together. Today I had to help my friend who need to consume a service from UrbanDictionary, a slang dictionary, using SOAP and JavaScript.

Actually there is an example of how to consume a service with JavaScript on their website too. However, it is still hard for a complete JavaScript newbies to understand and use.

So I had to code the skeleton part for my friend. Here is the code

function lookup(key, word) {
req = new XMLHttpRequest();
req.open("POST", "http://api.urbandictionary.com/soap", true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
var results = req.responseXML.getElementsByTagName("item");
var len = results.length;
var resp = "";
for(var i = 0 ; i < len ; i++)
{
var item = results[i];
for(var j = 0 ; j < item.childNodes.length ; j++)
{
var node = item.childNodes[j];
resp+="<br />";
if(node.nodeName == "word")
resp+= "คำว่า : " + node.firstChild.data;
else if(node.nodeName == "definition")
resp+= "คำจำกัดความ : " + node.firstChild.data;
else if(node.nodeName == "author")
resp += "ผู้แต่ง : " + node.firstChild.data;
else if(node.nodeName == "url")
resp += "URL : " + node.firstChild.data;


}
resp += "<hr />";
}
spanResp.innerHTML = resp;
}
}

var post = '<?xml version="1.0" encoding="UTF-8"?>' +
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<soapenv:Body>' +
'<ns1:lookup soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:UrbanSearch">' +
'<key xsi:type="xsd:string">' + escape(key) + '</key>' +
'<term xsi:type="xsd:string">' + escape(word) + '</term>' +
'</ns1:lookup>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';

req.setRequestHeader('Content-Type', 'text/xml');
req.send(post);
}

function doLookUp()
{
var oTxt = document.getElementById('txtWord');
lookup('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', oTxt.value);
}

You have to replace "xxxxxxxxxxxxxx" with your UrbanDictionary passkey to get this code working.

One of the problem I encountered during coding this example is the "getElementsByTagName" method. I first use the "getElementByTagName" (no 's' in 'Element') method which does not exist. It takes me a while to figure this out.