Calling WCF REST service from JavaScript

Technorati Tags: jquery,javascript,WCF,REST,.NET

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 );

}

This article is part of the GWB Archives. Original Author: Bob Goedkoop

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.