0

I have a WCF service hosted in IIS and returns JSON data properly when called through a browser.

I'm trying to consume the service via Jquery Ajax call. Both WCF and Jquery app are in same domain.

I have checked comments for a similar question :

Consuming a WCF Service in jQuery via AJAX Call in a different Project (Cross Domain) , unfortunately i could solve my problem from above.

My WCF Service Web.config

<system.serviceModel>
    <services>
      <service name="MyWCFService.Service1" behaviorConfiguration="MyWCFService.Service1Behavior">

        <endpoint address="Service1" 
                   binding="basicHttpBinding" 
                  contract="MyWCFService.IService1"/>

        <endpoint address="../Service1.svc"
                  binding="webHttpBinding"
                  contract="MyWCFService.IService1"
                  behaviorConfiguration="webBehaviour" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyWCFService.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

Method Signature:

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetEmployeeIDs/{value}")]
List<Employee> GetEmployeeIDs(String value);

Employee Class :

[DataContract]
public class Employee
{
    [DataMember]
    public string ID { get; set; }
}

Data returned when i hit below URL from broswer

URL : http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984

Result from Browser : 
{"GetEmployeeIDsResult":[{"ID":"239840"},{"ID":"239841"},{"ID":"239842"},{"ID":"239843"},{"ID":"239844"},{"ID":"239845"},{"ID":"239846"},{"ID":"239847"},{"ID":"239848"},{"ID":"239849"}]}

Jquery Call:

function Call_WCF_JSON() {
            var result = ""
            var ArgValue = '23984';

            $.getJSON("http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984", {},
                    function(data) {
                        alert(data);
                        console.log(data);

                });

            //GetEmployeeIDs is a function which has Value as String Argument  
            $.ajax({
                type: "GET",
                url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs",
                async: false,
                data: '{"value":"' + ArgValue + '"}',                    
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var oObj;
                    oObj = jQuery.parseJSON(data);
                    alert(oObj);
                    console.log(oObj);

                    var oRealObj;
                    oRealObj = jQuery.parseJSON(oObj.GetEmployeeIDsResult);
                    alert(oRealObj);
                    console.log(oRealObj);
                },
                failure: function (response) {
                    alert(response);
                    console.log(response);
                }
            });
        }

Edit 1 : Entire App is recreated with below code

Webconfig File with Single JSON Binding

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Emp_JSON_Srvc.Service1" behaviorConfiguration="Emp_JSON_Srvc.Service1Behavior">
        <endpoint address="../Service1.svc"
                  binding="webHttpBinding"
                  contract="Emp_JSON_Srvc.IService1"
                  behaviorConfiguration="webBehaviour" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Emp_JSON_Srvc.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

 </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Interface Code:

namespace Emp_JSON_Srvc
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetEmployeeIDs/{value}")]
        List<Employee> GetEmployeeIDs(String value);
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public string ID { get; set; }
    }
}

Service Class

namespace Emp_JSON_Srvc
{
    public class Service1 : IService1
    {

        public List<Employee> GetEmployeeIDs(String value)
        {
            List<Employee> results = new List<Employee>();
            results.Add(new Employee() { ID = "239840" });
            results.Add(new Employee() { ID = "239841" });
            results.Add(new Employee() { ID = "239842" });
            results.Add(new Employee() { ID = "239843" });
            results.Add(new Employee() { ID = "239844" });
            return results;
        }
    }
}

Result when i type URL in Browser

URL : http://localhost:60529/Service1.svc/GetEmployeeIDs/98 
(I have fixed the port number in Visual Studio. hence it wont change for each run)

{"GetEmployeeIDsResult":[{"ID":"239840"},{"ID":"239841"},{"ID":"239842"},{"ID":"239843"},{"ID":"239844"}]}

Javascript to Consume Json

function Call_WCF_JSON() {

    var result = ""
    alert('Method 1 : Start');
    $.getJSON("http://localhost:60529/Service1.svc/GetEmployeeIDs/98", {},
            function (data) {
                alert(data);
                console.log(data);
            });

    alert('Method 2 : Start');
    var query = { sValue: '98' };
    $.ajax({
        type: "POST",
        url: "http://localhost:60529/Service1.svc/GetEmployeeIDs/98",
        data: JSON.stringify(query),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert("Method 2 : Success");
            /*
            for (var i = 0; i < data.length; i++) {
            alert(data[i].Name);
            }
            */
        },
        error: function (e) {
            alert('Method 2 : Error');
            alert('Method 2 : --> ' + e.responseText);
        }
    });

    alert('Method 3 : Start');
    var value = '98'
    $.ajax({
        type: "GET",
        url: "http://localhost:60529/Service1.svc/GetEmployeeIDs/98",
        cache: false,
        data: JSON.stringify(value),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        processData: true,
        success: function (msg) {
            alert("Method 3 : Success");
            alert(JSON.stringify(msg));
        },
        error: function (err) {
            alert('Method 3 : Error');
        }
    })

    alert('Method 4 : Start');
    var ArgValue = '98';
    $.ajax({
        type: "GET",
        url: "http://localhost:60529/Service1.svc/GetEmployeeIDs",
        async: false,
        data: '{"value":"' + ArgValue + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert("Method 4 : Success");
            var oObj;
            oObj = jQuery.parseJSON(data);
            alert(oObj);
            console.log(data);

            var oRealObj;
            oRealObj = jQuery.parseJSON(oObj.GetHostServersResult);
            alert(oRealObj);
            console.log(oRealObj);

            //alert(data.GetHostServersResult[0].Name);
        },
        failure: function (response) {
            alert('Method 4 : Error');
            alert(response);
        }
    });
}

and the result i get from javascript is

Method 1 : Start
Method 2 : Start
Method 2 : Error
Method 2 : --> undefined
Method 3 : Start
Method 3 : Error
Method 4 : Start

any suggestions are appriciated.

Thank you !!

Community
  • 1
  • 1
Ramu
  • 343
  • 1
  • 6
  • 21
  • Why you do a `alert(data.d);`? In your example JSON response is no element `d`... – Jan Hommes Jun 24 '14 at 16:48
  • I've used same Jquery code for previous JSON data, and it worked when i returned a string value. Just tried out alert(data); it just gave me blank alert popup. edited my post to alert(data); instead of alert(data.d); – Ramu Jun 24 '14 at 16:51
  • yeah, but it gives you back JSON. Because you defined `dataType: "json"` it is allready a javascript object. To show something in your alert it need to look like this: `alert(data.GetEmployeeIDsResult[0].ID);`. Also try to check if there is a failure by adding a alert to the failure function. – Jan Hommes Jun 24 '14 at 17:25
  • Just tried to edit the code as :-- success: function (data) { result = data.GetEmployeeIDsResult[0].ID; alert(result); }, failure: function (response) { alert(response); } There seems no response mate. is there a way to check if javascript code is actually holding any data in data object? thank you!! – Ramu Jun 25 '14 at 07:50
  • My sincere apologies mate, there was an alert after ajax call to display result variable. that has shown as blank popup. Sorry for the confusion. I guess i'm not able to get any data from server / may be i am not handling data correctly. But i am sure Service is providing data when tested on browser – Ramu Jun 25 '14 at 10:30
  • Try to use [firebug](https://addons.mozilla.org/de/firefox/addon/firebug/) in firefox (or chrome debugger) and use `console.log(data);` and `console.log(response);` – Jan Hommes Jun 25 '14 at 11:39
  • @JanHommes : sorry mate, I am authorised to use firefox, got to live with IE 8 and more over i cannot add any plugin or so :( – Ramu Jun 26 '14 at 10:55

3 Answers3

1
this defaultOutgoingResponseFormat="Json" add

**

   <endpointBehaviors>
   <behavior name="EndpointVehavior">
      <enableWebScript/>
      <webHttp defaultOutgoingResponseFormat="Json"/>
    </behavior>
  </endpointBehaviors>

**

STORM566
  • 11
  • 1
0

This is a stringified response. Try to do something like :

var oObj;
oObj = jQuery.parseJSON(data);
var oRealObj;
oRealObj = jQuery.parseJSON(oObj.GetEmployeeIDsResult);

EDIT

I think the url that you provide the jQuery is wrong. this url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984", should be like url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs", and 23984 should be ta data section of jQuery.

So as to Consume a WCF service I provide you with the following link : How to consume Wcf Service in javascript?

EDIT 2

ok.. Let's try this one.

[OperationContract]
[WebInvoke(Method="POST",BodyStyle=WebMessageBodyStyle.Wrapped,ResponseFormat=WebMessageFormat.Json)]
List<Employee> GetEmployeeIDs(String value);

Now let's go to the client :

var query = { sValue: '23984'};

$.ajax({
    type: "POST",
    url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs",
    data: data:JSON.stringify(query),,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        for(var i=0; i<data.length;i++){
              alert(data[i].ID);
        }
    },
    error: function (e) {
        alert(e.responseText);
        return;
    }
 });
  • My sincere apologies mate, there was an alert after ajax call to display result variable which was missing in the above code i posted. that has shown as blank popup. Sorry for the confusion. I guess i'm not able to get any data from server / may be i am not handling data correctly. any suggestions please? – Ramu Jun 25 '14 at 10:31
  • take a look at my edit and tell me if you have any difficulties. – Emmanouil Chountasis Jun 25 '14 at 10:45
  • Thanks for your help mate, I have checked the link provided. Changed the script accordingly. Still no luck. I have updated the question with latest Javascript code. My WCF has 2 bindings basicHttpBinding and webHttpBinding, not sure if my javascript is getting confused which method to call. May be the way i'm calling in javascript refers only to webHttpBinding which outputs data in JSON format. – Ramu Jun 25 '14 at 13:58
  • provide us with the signature of the method in the WCF so as to take a look. Check that you have twice the "data" section. Data section is used to provide parameters and it must be a json string. ex Let's say that the signature is "String Test(String sValue)". In JavaScript create var query = { sValue: 'test1234', }; then in the ajax call say "data:JSON.stringify(query)," – Emmanouil Chountasis Jun 25 '14 at 14:16
  • Sorry mate that was remained by mistake, i have edited it now. Also appended the method signature to my question now. Thank you!! – Ramu Jun 25 '14 at 16:41
  • ok, regarding the service signature i have replaced with GET with POST and removed UriTemplate = "GetEmployeeIDs/{value}". When tried to access the service in browser it says, Endpoint not found. Seems like we need to have it for serving JSON response. Coming to client now the control got transfered to Error Method and alert(e.responseText); says "Undefined". Thanks for your support mate – Ramu Jun 25 '14 at 20:40
  • Ok, it looks like you must either change your config file or use the UriTemplate. Till now all WCF that I have created do not use UriTempalte, i prefer to use config to serve endpoints (but I haven't used multiple endpoints). If I was you I would try to create a simple WCF with one endpoint so as to see that my ajax can communicate with the service. Then I would try to understand why the second endpoint could provoke so many problems! – Emmanouil Chountasis Jun 26 '14 at 06:35
  • I have re-created all the code and posted under Edit 2 of my question and its response when executed. Not sure where iam going wrong. Thanks for your time – Ramu Jun 26 '14 at 12:20
0

You are using POST for a GET request. Try to change your ajax call to:

function Call_WCF_JSON() {
    var result = ""
    $.ajax({
        type: "GET",
        url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        failure: function (response) {
            console.log("Error");
            console.log(response);
        }
    });
}

To show the console.log message use a debugger. For example firebug in Firefox or Chrome (just hit F12).

EDIT:
To debug AJAX request, have a look at the firebug console. There should be an Request like the following: enter image description here Check the HTTP-Status (yellow). Is it 200, everything works fine. Then have a look into the response (you find it by clicking the + and navigate to the response tab). What does it say? Please show us a screen of your firebug console if you still have problems.

Jan Hommes
  • 5,122
  • 4
  • 33
  • 45
  • Thanks for youe help mate, i have changed from POST to GET. Yet no Joy. I have edited the question with my latest update – Ramu Jun 25 '14 at 13:49
  • I got to use only IE 8 mate, cannot use other than IE :( – Ramu Jun 25 '14 at 16:43