Geeks With Blogs
Bob Goedkoop Programming C# on Microsoft's .NET plaform

Technorati Tags: ,,,,
Without further ado, here is a javascript class that can be used to call a WCF REST web service:
 
// ----------------------------------------
// ----------------------------------------
// Class WcfService
//
// Dependencies:
//  JQuery
//
 
// ----------------------------------------
// Constants
// ----------------------------------------
 
WcfService.URL_LOCATION_LOCAL   = document.location.protocol + "//" + document.location.host + "/";
WcfService.DATATYPE_JSON        = 'json';
WcfService.CONTENTTYPE_JSON     = 'application/json; charset=utf-8';
WcfService.MSG_PREFIX            = 'WcfService.js, ';
 
 
// ----------------------------------------
// "Private" section
// ----------------------------------------
 
WcfService._getNowAsString = function()
{
    var currentdate = new Date(); 
    var now = currentdate.getDate()                + "/"
            + ( currentdate.getMonth() + 1 )    + "/" 
            + currentdate.getFullYear()            + "@"  
            + currentdate.getHours()            + ":"  
            + currentdate.getMinutes()            + ":" 
            + currentdate.getSeconds()
    ;
    return now;
}
 
WcfService.prototype._showDebugMessage = function( msg )
{
    //msg = WcfService._getNowAsString() +", " + WcfService.MSG_PREFIX + msg;
    //alert( msg );
}
 
 
WcfService.prototype._callFailed = function ( xhr, statusCodeText, statusText ) {
 
    var msg = "Service call failed: ";
 
    if ( xhr )
    {
        msg =    msg 
            +    statusText + " (" + statusCodeText + " [" + xhr.status + "])"
            +    "\n\n" 
            +    xhr.responseText
        ;
    }
    else
    {
        msg = msg + "reason unknown";
    }
 
    msg = WcfService._getNowAsString() +", " + WcfService.MSG_PREFIX + msg;
    alert( msg );
}
 
 
WcfService.prototype._callSucceeded = function( result )
{
    var msg= 
        this._getNowAsString() +", " + 
        WcfService.MSG_PREFIX + 
        "Service call succeeded ["+ result +"]"
    ;
    alert( msg );
}
 
 
// Unwrap (.NET ".d") and deserialize result.
WcfService.prototype._unwrapResult = function( result )
{
    var unwrappedResult = result;
    if ( result.hasOwnProperty( "d" ) )
    {
        unwrappedResult = $.parseJSON( result.d ); 
    }
    return unwrappedResult;
}
 
 
 
//
// Method to call a WCF service
//
// Arguments:
//  string type        - GET, POST, PUT or DELETE verb
//  string url         - Location of the service, i.e.: "Service.svc/GetUser";
//  string data        - Data sent to server, i.e.: '{"Id": "' + userid + '"}'
//  string contentType - content type sent to server
//  string dataType    - Expected data format from server
//  bool processData   - True or False
//
WcfService.prototype._call = function ( type, url, data, contentType, dataType, processData, doSuccess, doError )
{
    this._showDebugMessage( 
        "_call( '"+type+"', '"+url+"', '"+data+"', '"+contentType+"', '"+dataType+"', '"+processData+"', doSuccess, doError )" +
        "\n\n" +
        "async ["+ this.async +"]"
    );
    
    var jqxhrPromise = $.ajax( {
                            cache: false,
                            async: this.async,
                            type: type,
                            url: url,
                            data: data,
                            contentType: contentType,
                            dataType: dataType,
                            processdata: processData,
                            success: function ( result )
                            {
                                var svc = new WcfService()
                                svc._showDebugMessage( "result [" + result +"]"  );
                                result = svc._unwrapResult( result );
 
                                if ( doSuccess == undefined )
                                {
                                    doSuccess = svc._callSucceeded;
                                }
                                
                                setTimeout( function () {
                                    // Delay ecxecution of success handler.
                                    // Mainly done to see any visual feedback in the browser.
                                    doSuccess( result );
                                }, 1000 ); 
                            },
                            error: function ( xhr, statusCodeText, statusText )
                            {
                                var svc = new WcfService()
                                svc._showDebugMessage( "error ["+xhr+"] ["+statusCodeText+"] ["+statusText+"]" );
 
                                if ( doError == undefined )
                                {
                                    doError = svc._callFailed;
                                }            
                                doError( xhr, statusCodeText, statusText );
                            }
    } );
    
    return jqxhrPromise;
}
 
// ----------------------------------------
// Constructor(s)
// ----------------------------------------
 
function WcfService()
{
    this.urlServiceLocation = WcfService.URL_LOCATION_LOCAL;
    this.contentType = WcfService.CONTENTTYPE_JSON;
    this.dataType = WcfService.DATATYPE_JSON;
    this.async = true;
    this.processData = false;
}
 
// ----------------------------------------
// "public" section
// ----------------------------------------
 
WcfService.prototype.post = function ( url, data, doSuccess, doError )
{
    return this._call( "POST", url, data, this.contentType, this.dataType, this.processData, doSuccess, doError );
}
 
WcfService.prototype.get = function ( url, data, doSuccess, doError )
{
    return this._call( "GET", url, data, this.contentType, this.dataType, this.processData, doSuccess, doError );
}
Posted on Tuesday, November 26, 2013 3:15 PM jquery , javascript , WCF , REST | Back to top


Comments on this post: Calling WCF REST service from JavaScript

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Bob Goedkoop | Powered by: GeeksWithBlogs.net