Click here to Skip to main content
15,879,326 members
Articles / Web Development / HTML
Tip/Trick

How to call WCF service using simple JavaScript

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
24 Dec 2010CPOL 30.4K   7   6
WCF service
Hello ,

Although there are lot of ways (like Jquery, etc.) to make Ajax request to access WCF service or any service, I implement a neat and clean way to call WCF service in JSON Format.

C#
// base URL for the Ajax call to service
var baseUrl = "http://localhost:54976/RestServiceImpl.svc/";
//Ajax request function for making Ajax calling through other object
function AjaxRequest(baseurl, type, callbackResponse, parameterString) {
    this.BaseURL = baseurl;
    this.Type = type;
    this.Callback = callbackResponse;
    this.createXmlRequestObject();
    this.ParemeterString = parameterString;
}
// Create XMLHTTP OBJECT
AjaxRequest.prototype.createXmlRequestObject = function() {
    if (window.ActiveXObject) { // INTERNET EXPLORER
        try {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            this.xmlHttp = false;
        }
    }
    else { // OTHER BROWSERS
        try {
            this.xmlHttp = new XMLHttpRequest()
        } catch (f) {
            this.xmlHttp = false;
        }
    }
    if (!this.xmlHttp) { // RETURN THE OBJECT OR DISPLAY ERROR
        alert('there was an error creating the xmlhttp object');
    } else {
        //return this.xmlhttp;
    }
}
AjaxRequest.prototype.MakeRequest = function() {
    try {
        // PROCEED ONLY IF OBJECT IS NOT BUSY
        if (this.xmlHttp.readyState === 4 || this.xmlHttp.readyState === 0) {
            // EXECUTE THE PAGE ON THE SERVER AND PASS QUERYSTRING
            this.xmlHttp.open(this.Type, this.BaseURL, false);
            var that = this;
            // DEFINE METHOD TO HANDLE THE RESPONSE
            this.xmlHttp.onreadystatechange = function() {
                try {
                    // MOVE FORWARD IF TRANSACTION COMPLETE
                    alert(that.xmlHttp.readyState);
                    if (that.xmlHttp.readyState == 4) {
                        alert(that.xmlHttp.status);
                        // STATUS OF 200 INDICATES COMPLETED CORRECTLY
                        if (that.xmlHttp.status == 200) {
                            // WILL HOLD THE XML DOCUMENT
                            var xmldoc;
                            if (window.ActiveXObject) { // INTERNET EXPLORER
                                xmldoc = new ActiveXObject("Microsoft.XMLDOM");
                                xmldoc.async = "false";
                                that.Callback(that.xmlHttp.responseText);
                            }
                            else { // OTHER BROWSERS
                                //writeMessage("MakeRequest", that.xmlHttp.responseText);
                                that.Callback(that.xmlHttp.responseText);
                            }
                        }
                    }
                }
                catch (e)
                { alert(e) }
            }
            switch (this.Type) {
                case "GET":
                    //this.xmlHttp.setRequestHeader("Content-type", "application/json");
                    // MAKE CALL
                    this.xmlHttp.send(this.BaseURL);
                    break;
                case "POST":
                    this.xmlHttp.setRequestHeader("Content-type", "application/json");
                    this.xmlHttp.send(this.ParemeterString)
            }
        }
        else {
            // IF CONNECTION IS BUSY, WAIT AND RETRY
            setTimeout('GetAllAppsService', 5000);
        }
    } catch (e) {
        alert(e);
    }
}


Here ajaxrequest is the function where we treated it as a class.
Let me give an overview on parameters of ajaxrequest:

BaseURL: Base url is the service url .
Type: Which kind of request "GET" or "POST".
Callbackresponse: Callback response used as callback function for calling from object and this will hold the response of server after sending the request.
Parameterstring: Parameter string is the body of the request.
Note: If request is in JSON format, then ParameterString should be JSON string (in case of POST Request).

Now I will explain how to call it.

C#
AuthenticateLogin.prototype.SendDetailsToServer = function(parameters, localId) {
    var url = baseUrl + "SignUpUser";
    var parameterString = "{";
    for (var i = 0; i < parameters.length; i++) {
        parameterString = parameterString + '"'
                  + parameters[i][0] + '":"'
                  + parameters[i][1] + '" ,';
    }
    parameterString = parameterString.slice(0, parameterString.length - 1);
    //writeMessage("AddNewReminderToServer", "Local id : "+localId);
    parameterString = parameterString + "}";
    var ajaxRequestObject = new AjaxRequest(url, "POST", function(responseText) {
        var jsonobj = eval('(' + responseText + ')');
        var result = jsonobj.SignUpUserResult;
        if (result == "Successful") {
            alert("SuccessfullyMail sent and you will redirect to login Page");
            window.location = "http://localhost:54976/UI/latestLogin.htm";
        }
        else {
            alert("Message sending Fail! Please try again");
            window.location.reload(true);
        }
        //        writeMessage("handleresponse", jsonstr);
        //        writeMessage(" -> local id :", ajaxRequestObject.TempItemID);
    }, parameterString);
    //writeMessage("AddNewReminderToServer", "Local id in ajax object : " + ajaxRequestObject.TempItemID);
    ajaxRequestObject.MakeRequest();
}


That's it. I hope you will like it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
Rohit started Embedded Programing in his college days and now he is a Software Developer by Profession. Mainly he interested in cutting edge technology offer by Microsoft (i.e Azure,MVC). He Loves coding and his passion is always been towards Microsoft Technologies. Apart from coding his other hobbies include reading books and hang out with friends is his most favorite past time hobby.


1. 20 Apr 2014: Best Mobile Article of March 2014 - First Prize

Comments and Discussions

 
GeneralI dont know why you voted down. Anyway. this is just tip and... Pin
maq_rohit25-Dec-10 23:58
professionalmaq_rohit25-Dec-10 23:58 
GeneralReason for my vote of 1 WCFm what? Where? For calling what k... Pin
Manfred Rudolf Bihy25-Dec-10 23:04
professionalManfred Rudolf Bihy25-Dec-10 23:04 
Generalthanks Walt :) Pin
maq_rohit25-Dec-10 7:51
professionalmaq_rohit25-Dec-10 7:51 
GeneralReason for my vote of 5 I didn't think it was hard to unders... Pin
Dr.Walt Fair, PE25-Dec-10 7:43
professionalDr.Walt Fair, PE25-Dec-10 7:43 
GeneralCan you tell me in which part, It is difficult? I will reall... Pin
maq_rohit23-Dec-10 6:48
professionalmaq_rohit23-Dec-10 6:48 
GeneralReason for my vote of 3 difficult to understand Pin
Sandesh M Patil23-Dec-10 6:04
Sandesh M Patil23-Dec-10 6:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.