DCSIMG
How to call Web/WCF Services without ScriptManager - new { Name = ”Shay Jacoby” }

new { Name = ”Shay Jacoby” }

Maximum separation, minimum Dependencies, No Injections.

How to call Web/WCF Services without ScriptManager

Hi, 

I wrote a generic client-side javascript in order to simplify the work with Web/WCF Services.

Script Benefits (or Why do you need such a script...?):

1. If you use this script, You don't need to use ScriptManager or any form runat="server" in order to consume a Web/WCF Service. The unnesesery viewstate increase your page.

2. You can call a Web/WCF Service from any static HTML file.

3. Very light script (1.4 k) , the ScripyManager generated output scripts are much larger.

4. The must be some more good reasons to use it ( but it late and I'm tired).

I attached the Ajaxlib.js as attachment for download.

Enjoy it!


Here are 2 "real world" examples of the script usage:

 /*start method that calls a WCF service */

function GetZip(city, address, houseNum)

 

{

if (!IsEmpty(city) && !IsEmpty(address) && !IsEmpty(houseNum))

 

{

 

// Service url

var url = "ServiceModel/ZipService.svc/ZipSelectByAddress";

 

// Service params

var params = "city=" + escape(city);

 

params = params + "&address=" + escape(address);

params = params + "&houseNum=" + escape(houseNum);

 

//target Object, object that will be available in the callback method, e.g. "myDivID".

var targetObject = "txtsZip";AJAX.init("GET", url, onGetZipCompleted, params, targetObject)

 

}

 

}

 

 

 

//callback method to process results from xml http object

function onGetZipCompleted(responseText, targetObject)

 

{

var resInput = document.getElementById(targetObject);

 

// Eval JSON response into variable

var obj = eval('(' + responseText + ')');

 

var res = obj["d"];

if (res =='0')res = '00000';

 

resInput.value = res;

 

}

 

 

/*end of method that calls a WCF service*/

 

 Web Service example, i use the XML output option:

 

/* Web Service call */

function getFiles(id)

{

if (id > 0)

{

//Build url with params

var url = "/Services/FileManagerInfoService.asmx/GetFiles";

var params = "id=" + id;

AJAX.init("GET", url, onGetFilesCompleted, params, "divUploads", "XML");

}

}

function onGetFilesCompleted(res, targetObject){
document.getElementById(targetObject).innerHTML = res;
}

/* End of Web Service call */

 

  

/*--------start Ajaxlib.js-----------*/

 

/* Written by Shay Jacoby (s-online.co.il) */
AJAX = {
xmlHttp:'', 
targetObject:null,
outputFormat:'XML',
init : function(methodType, url, callback, params, targetObject, outputFormat){ 
AJAX.xmlHttp=AJAX.getXmlHttpObject();
 
if (AJAX.xmlHttp==null){
    alert ("Your browser does not support AJAX!");
    return;
} 
 
if (methodType=="GET" && params!=null){
    url = url + "?" + params;
}
 
if (outputFormat!=null)
    AJAX.outputFormat = outputFormat;
 
AJAX.targetObject = targetObject;
 
AJAX.xmlHttp.open(methodType,url,true);
 
if (methodType=="POST" && params!=null){
    if (outputFormat=="JSON"){
        AJAX.xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        //Convert params to Json format
        params = AJAX.toJsonParams( params );
    }
    else {
        AJAX.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        AJAX.xmlHttp.setRequestHeader("Content-length", params.length);
        AJAX.xmlHttp.setRequestHeader("Connection", "close");
    }  
}
 
//not tested:
//AJAX.xmlHttp.setRequestHeader("Pragma", "no-cache");
//AJAX.xmlHttp.setRequestHeader("Cache-Control", "no-cache");
 
AJAX.xmlHttp.onreadystatechange=function(){AJAX.stateChanged(callback)};
 
AJAX.xmlHttp.send(params);
},
 
stateChanged : function(callback){
    // Returns the status of the request:
    // 0 uninitialized, 1 loading, 2 loaded, 3 interactive, 4 complete 
    if (AJAX.xmlHttp.readyState==4){
        //purposes we are only interested in OK (200) response.
        if (AJAX.xmlHttp.status == 200){
            switch(AJAX.outputFormat){
                case "JSON":
                    if (callback) callback(AJAX.xmlHttp.responseText, AJAX.targetObject);
                    break;
                case "XML":
                    if (callback) callback(AJAX.xmlHttp.responseXML, AJAX.targetObject);
                    break;
            }
        } 
        else {
            // there was a problem with the request, for example the response may 
            // be a 404 (Not Found) or 500 (Internal Server Error) response codes.
            alert('ERROR: ' + AJAX.xmlHttp.statusText + ' (' + AJAX.xmlHttp.status + ')');
            return;
        }
    }
},
 
//method: Convert parameters to Json Format e.g. {"param1":"param1Value", "param2":"param2Value"}
toJsonParams : function(qStr){
 
    if (qStr==null || qStr.length==0)
        return "{''}";
 
    var output = "{";
    var params = qStr.split("&");
    for (i=0;i<params.length;i++) {
        var prmArr = params[i].split("=");
        output += "\""  + prmArr[0] +  "\"";
        output += ":";
        output += "\""  + prmArr[1] +  "\",";
    }
     if (output.indexOf(',' > 0))
        output = output.slice(0, -1);
    output += "}";
    return output;
},
 
getXmlHttpObject : function(){
    AJAX.xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari, IE7
        AJAX.xmlHttp=new XMLHttpRequest();
    }
    catch (e){
        // Internet Explorer
        try{
            AJAX.xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){
            AJAX.xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return AJAX.xmlHttp;
    }
}

 

 

 

/*--------End Ajaxlib.js-----------*/

תוכן התגובה

Guy Burstein כתב/ה:

Hi

It is very difficult to the code you posted via RSS. Are you familiar with "Copy Source as Html" Add in?

Guy

# August 4, 2008 12:57 AM

שי יעקובי כתב/ה:

Thanks, I installed the add inn and pasted the code again.

# August 4, 2008 4:24 AM

Basil Goldman כתב/ה:

Hi Shai

I liked your prototyped style of the code, and new feature for WCF.

Good job!!!

Might be you can insert source using www.manoli.net/csharpformat - web page from Manoli too.

Don't be shy to publish posts...

Thanks

# August 28, 2008 3:25 PM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 2 and 4 and type the answer here:


Enter the numbers above: