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 !!

7
  • Why you do a alert(data.d);? In your example JSON response is no element d... Commented Jun 24, 2014 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); Commented Jun 24, 2014 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. Commented Jun 24, 2014 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!! Commented Jun 25, 2014 at 7: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 Commented Jun 25, 2014 at 10:30

3 Answers 3

1
this defaultOutgoingResponseFormat="Json" add

**

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

**

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Thanks for youe help mate, i have changed from POST to GET. Yet no Joy. I have edited the question with my latest update
I got to use only IE 8 mate, cannot use other than IE :(
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;
    }
 });

8 Comments

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?
take a look at my edit and tell me if you have any difficulties.
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.
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),"
Sorry mate that was remained by mistake, i have edited it now. Also appended the method signature to my question now. Thank you!!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.