0

I am learning WCF service. I am trying to call an RESTful service from Jquery. My Service is as below

Service Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;

namespace RESTfulServiceLib
{
[AspNetCompatibilityRequirements(RequirementsMode
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestFullService : IRestFullService
{
    public string Welcome(string Name)
    {
        return  "Welcome to Restful Service " + Name;
    }
}
}

Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;

namespace RESTfulServiceLib
{

[ServiceContract]

public interface IRestFullService
{
    [OperationContract]
    [WebInvoke(UriTemplate="/Welcome/{Name}",Method="GET",ResponseFormat=WebMessageFormat.Json)]
    string Welcome(string Name);
}
}

I have created a service host and the svc file goes like this

<%@ ServiceHost Language="C#" Debug="true" Service="RESTfulServiceLib.RestFullService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

I have the following config settings

<configuration>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
    <behaviors>
        <endpointBehaviors>
            <behavior name="EndPBhvr">
                <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
                    faultExceptionEnabled="true" />

            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="SvcBhvr">
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
        <service name="RESTfulServiceLib.RestFullService">
            <endpoint address="" behaviorConfiguration="EndPBhvr"
                binding="webHttpBinding" bindingConfiguration="" name="EP1"
                contract="RESTfulServiceLib.IRestFullService" />
        </service>
    </services>
</system.serviceModel>
</configuration>

After running the application , when I am browsing the url "http://localhost:2319/RESTFullService.svc/welcome/Mahesh" it is returning the value as

"Welcome to Restful Service Mahesh"

I have tried to call this service using Jquery. But I am getting

error 200 undefined

The script is as follows

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.4.min.js"></script>
<script >
function ajaxcall()
{
    $.ajax({
        url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType:"jsonp",
        data:{},
        processdata : true,
        success: function(response)
        {
            var data= response.d;
            alert(data);
        },

        error: function(e)
        {
            alert('error '+e.status + ' ' + e.responseText);
        }
    });
}
$().ready(function(){
    $('#btntest').click(ajaxcall);
})  
</script>
</head>
<body>
<button id="btntest" >Click Me</button>
</body>
</html>

What is wrong in my coding? Please help me...

Thanks

Mahesh

1
  • I have added 'alert(XMLHttpRequest.responseText);' and 'alert(e.statusText);' additionally to error section now and tried. Now the e.statusText was displaying 'Success'. What it means? Commented Dec 7, 2012 at 10:26

3 Answers 3

1

In the Success of your jQuery you have used

// var data= response.d;

but your are not returning a valid json. there is no "d" in your response.

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

1 Comment

Thank you for the reply. I tried with 'alert("succeed")' in the success section. But I am getting the same error. I think,the service is not succeeding due to some other error
0

It is due to the Cross Domain Issue. I did a couple of changes in config file and it worked fine

The config file after changes. Added new Binding Configuration with crossDomainScriptAccessEnabled="true" and added to the endpoint. And put the aspNetCompatibilityEnabled="false"

<configuration>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
    <standardEndpoints />
    <bindings>
        <webHttpBinding>
            <binding name="Bind1" crossDomainScriptAccessEnabled="true" />
        </webHttpBinding>
    </bindings>
    <behaviors>
        <endpointBehaviors>
            <behavior name="EndPBhvr">
                <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
                    faultExceptionEnabled="true" />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="SvcBhvr">
                <serviceMetadata httpGetEnabled="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
    <services>
        <service behaviorConfiguration="SvcBhvr" name="RESTfulServiceLib.RestFullService">
            <endpoint address="" behaviorConfiguration="EndPBhvr" binding="webHttpBinding"
                bindingConfiguration="Bind1" name="EP1" contract="RESTfulServiceLib.IRestFullService" />
        </service>
    </services>
</system.serviceModel>
</configuration>

Modified script, i have added "?callback=?" at the end of the URL to get the output in JSON instead of JSONP. JSONP will work without giving the callback in the URL

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" language="javascript">
    function ajaxcall()
    {
        $.ajax({
            url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh?calback=?",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            success: function (response) {
                var data = response;
                alert(data);
            },

            error: function (e) {
                alert('error ' + e.status + ' ' + e.responseText);

            }
            });
    }

    $().ready(function(){
        $('#btntest').click(ajaxcall);
    })  
</script>
</head>
<body>
    <button id="btntest" >Click Me</button>
</body>
</html>

Thanks to my colleague Mrs.Poorani in Calsoft Labs for helping me in solving this issue

Comments

0
function CallService(sucessData) {
$.ajax({
    // Add code for Cross Domain
    headers: getHeaders(),
    type: varType, //GET or POST or PUT or DELETE verb
    url: varUrl, // Location of the service
    data: varData, //Data sent to server
    contentType: varContentType, // content type sent to server
    dataType: varDataType, //Expected data format from server
    processdata: varProcessData, //True or False
    crossDomain: true,
    cache: varCache,
    timeout: 200000,
    success: sucessData,
    error: function (xhr) {// When Service call fails
        fancyAlert("Error: " + xhr.responseText);
        //fancyAlert('Error occured in Service Call');
    }
});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.