Wednesday, August 25, 2010

Simple soap client

Below is a simple javascript soap client. The same code can be modified to work as an ajax client by removing the SOAPAction header. The below code accepts the service URL, soap envelope, SOAPAction header name (because it may be of different case in different technology), action and method.

Javascript example
<html>
<head>
<title>Soap Client</title>
<script>
var READY_STATE_UNINITIALIZED=0;
var READY_STATE_LOADING=1;
var READY_STATE_LOADED=2;
var READY_STATE_INTERACTIVE=3;
var READY_STATE_COMPLETE=4;
var xmlHttpRequest;
function getXmlHttpRequest()
{
 var xRequest=null;
 if (window.XMLHttpRequest)
 {
  xRequest=new XMLHttpRequest();
 }
 else if (typeof ActiveXObject != "undefined")
 {
  xRequest=new ActiveXObject("Microsoft.XMLHTTP");
 }
 return xRequest;
}
function handleEmptyString(value,userMessage)
{
    var status=false;
    if(value == "")
    {
        alert(userMessage);
    }
    else
    {
        status=true;
    }
    return status;
}
function sendRequest(url,soapActionHeaderName,
                        soapAction,params,httpMethod,contentType)
{
    var status=false;
    status=handleEmptyString(url,"Please enter the URL.");
    if(status == true)
    {
        status=handleEmptyString(soapActionHeaderName,"Please enter the Soap action header name.");
        if(status == true)
        {
            status=handleEmptyString(soapAction,"Please enter the Saop action.");
            if(status == true)
            {
                status=handleEmptyString(params,"Please enter the soap request.");
                if(status == true)
                {
                    status=handleEmptyString(contentType,"Please enter the content type.");
                }
            }
        }
    }
    if(status==true)
    {
        //Disable mozilla security restriction
        if(window.netscape &&
        window.netscape.security.PrivilegeManager.enablePrivilege)
        {
            var pm=netscape.security.PrivilegeManager;
            pm.enablePrivilege('UniversalBrowserRead');
        }
        // If method not set
        if (!httpMethod)
        {
            httpMethod="GET";
        }
        xmlHttpRequest=getXmlHttpRequest();
        if (xmlHttpRequest)
        {
            xmlHttpRequest.onreadystatechange=onReadyStateChange;
            xmlHttpRequest.open(httpMethod,url,true);
            xmlHttpRequest.setRequestHeader(
            "Content-Type",contentType);
            xmlHttpRequest.setRequestHeader(soapActionHeaderName,soapAction);
            xmlHttpRequest.send(params);
        }
    }
}
function onReadyStateChange()
{
    var ready=xmlHttpRequest.readyState;
    var data=null;
    if (ready==READY_STATE_COMPLETE)
    {
        data=xmlHttpRequest.responseText;
        //... do something with the data...
        document.getElementsByName("taResponse")[0].value=data;
    }
    else
    {
        data="Loading...["+ready+"]";
        document.getElementsByName("taResponse")[0].value=data;
    }
}
function sendData()
{
    var url=document.getElementsByName("txtURL")[0].value;
    var params=document.getElementsByName("taRequest")[0].value;
    var httpMethod=document.getElementsByName("txtMethod")[0].value;
    var soapActionHeaderName;
    soapActionHeaderName=document.getElementsByName("txtActionHeaderName")[0].value;
    var soapAction=document.getElementsByName("txtAction")[0].value;
    var contentType=document.getElementsByName("txtContentType")[0].value;
    sendRequest(url,soapActionHeaderName,soapAction,params,httpMethod,contentType);
}
function clearData()
{
    document.getElementsByName("taResponse")[0].value="";
}
</script>
</head>
<body>
<h1>Soap client</h1>
<table>
<tr>
<tr>
<td>URL: (e.g. http://xyz.com/service)</td>
<td><input type="text"
value="http://localhost:8080/CalculatorProj/services/Calculator"
name="txtURL" size="150"/></td>
</tr>
<td>Request:</td>
<td><textarea rows="12" cols="120" name="taRequest">
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:q0="http://wtp" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <q0:add>
      <q0:number1>5</q0:number1>
      <q0:number2>6</q0:number2>
    </q0:add>
  </soapenv:Body>
</soapenv:Envelope>
</textarea>
</td>
</tr>
<tr>
<td>Action header name:</td>
<td><input type="text" value="SOAPAction" name="txtActionHeaderName"/></td>
</tr>
<tr>
<td>Action:</td>
<td><input type="text" value="add" name="txtAction"/></td>
</tr>
<tr>
<td>Content type:</td>
<td><input type="text" value="text/xml; charset=utf-8" name="txtContentType" /></td>
</tr>
<tr>
<td>Method: (GET/POST)</td>
<td><input type="text" value="POST" name="txtMethod"/></td>
</tr>
<tr>
<td>Response:</td>
<td><textarea rows="8" cols="120" name="taResponse"></textarea></td>
</tr>
<tr>
<td></td>
<td align="center">
    <input type="button" value="Send" onclick="sendData()"/>
    <input type="button" value="Clear Result" onclick="clearData()"/>
</td>
</tr>
</table>
</body>
</html>

Note: This code sample works only with in your domain. If you want to try across domain then please refer Google AJAX APIs.

Google gadget

Goto www.google.com and locate iGoogle (top right).
Sing In to iGoogle. Play around with the default gadgets on iGoogle.

Install Google Gadget Editor.

Read how-to-make-google-gadgets and make your first Google gadget.

Refer Google Gadgets for more info.

Monday, August 23, 2010

Reading cross domain JSON (AJAX)

If you want to read JSON content from a different domain, let us say you want to read JSON content from http://twitter.com, then here is a simple example using JQUERY JSON API.

http://twitter.com JSON content link is http://api.twitter.com/1/statuses/public_timeline.json?callback=?.

Javascript example with jQuery.each() loop
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
var JSONPUBICURL="http://api.twitter.com/1/statuses/public_timeline.json?callback=?";
var TWITTERURL="http://twitter.com/";
function getJSON()
{
var strHTML='';
var imgURL="";
$.getJSON(JSONPUBICURL,
function(data){
strHTML+='<table border="0px">';
$.each(data, function(i, item) {

    imgURL=item.user["profile_image_url"];

    strHTML+='<tr>';
    strHTML+='<td valign="top">';
    strHTML+='<img src="'+imgURL+'" alt="'+item.user["screen_name"]+'" title="'+item.user["screen_name"]+'" height="50px" width="50px"/>';
    strHTML+='</td>';
    strHTML+='<td valign="top" >';
    strHTML+='<a href="'+TWITTERURL+item.user["screen_name"]+'/statuses/'+item.id+'" target="_blank" >'+item.text+'</a><br/>';
    strHTML+=item.created_at+' [via '+item.source+']<br/>';
    strHTML+='</td>';
    strHTML+='</tr>';
});
strHTML+='</table>';
strHTML+='<div align="right" ><a href="'+TWITTERURL+'" target="_blank">more...</a></div>';
document.getElementById("tweets").innerHTML=strHTML;
});
}
</script>
<div id="tweets"></div>
<script>
    $(document).ready(getJSON());
</script>

Note: using this approach you can get the live tweets from http://twitter.com.


Javascript example with for loop
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
var JSONPUBICURL="http://api.twitter.com/1/statuses/public_timeline.json?callback=?";
var TWITTERURL="http://twitter.com/";
function getJSON()
{

var strHTML='';
var imgURL="";

$.getJSON(JSONPUBICURL,
function(data){
strHTML+='<table border="0px">';
var length=data.length;
for(var i=0;i<length;i++)
{
    imgURL=data[i].user["profile_image_url"];
    strHTML+='<tr>';
    strHTML+='<td valign="top">';
    strHTML+='<img src="'+imgURL+'" alt="'+data[i].user["screen_name"]+'" title="'+data[i].user["screen_name"]+'" height="50px" width="50px"/>';
    strHTML+='</td>';
    strHTML+='<td valign="top" >';
    strHTML+='<a href="'+TWITTERURL+data[i].user["screen_name"]+'/statuses/'+data[i].id+'" target="_blank" >'+data[i].text+'</a><br/>';
    strHTML+=data[i].created_at+' [via '+data[i].source+']<br/>';
    strHTML+='</td>';
    strHTML+='</tr>';

}
strHTML+='</table>';
strHTML+='<div align="right" ><a href="'+TWITTERURL+'" target="_blank">more...</a></div>';
document.getElementById("tweets").innerHTML=strHTML;

});

}
</script>
<div id="tweets"></div>
<script>
    $(document).ready(getJSON());
</script>

for loop may be faster than jQuery.each() loop. see jQuery tests in Low Level JavaScript Performance.