Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post data to WCF Service using jquery Ajax?

I am facing issue in consuming WCF service using JQUERY AJAX. I know this is cross domain issue and have read alot of solution about it. but none worked for me. Below is all the related code. Can anyone please help me out?

Thanks

 [OperationContract]
        [WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json)]
        [return: MessageParameter(Name = "result")]


        public ServiceSearchResponse GetSearchResults(ServiceSearchParams sParams)
        {
            /// search function
        }

JQUERY:

        $.ajax({
            type: 'POST',
            url: "http://myserviceurl.com/GetSearchResults",
            data: p,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            crossDomain: true,
            success: function (data) {

                alert(data);
            },
            failure: function (response) {
                alert('failed');
            },
            error: function (response) {
                alert(JSON.stringify(response));
            }
        });

Webconfig:

  <system.webServer>        
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>

<system.serviceModel>
    <protocolMapping>
      <add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
    </protocolMapping>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultServiceBehavior">
          <!--Added DefaultServiceBehavior referenced at service tag above-->
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>       
        <behavior name="myserives.services.AppServicesAspNetAjaxBehavior">

          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>  
      <service name="mypackage.services.MyServices">
        <endpoint address="" behaviorConfiguration="myserives.services.AppServicesAspNetAjaxBehavior" binding="webHttpBinding"
           bindingConfiguration="LargeSizeMessages" contract="myContractName"  />
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="LargeSizeMessages" maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647" crossDomainScriptAccessEnabled="true">      
          <security mode="None" />
        </binding>
      </webHttpBinding>

    </bindings>

  </system.serviceModel>

This is how it looks like: http://screencast.com/t/b7tsqld6

See error : http://screencast.com/t/pWQNAlmMYS3

And nothing in post data. though i m posting data.

--- UPDATE

See my Global.asax .. i am doing something wrong here:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {

            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetNoStore();

            EnableCrossDmainAjaxCall();
        }

        private void EnableCrossDmainAjaxCall()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
                          "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                              "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials",
                             "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                              "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                              "1728000");
                HttpContext.Current.Response.End();
            }
        }
like image 840
Irfan TahirKheli Avatar asked Sep 28 '22 12:09

Irfan TahirKheli


People also ask

Can we call WCF service from JavaScript?

Whenever you need to consume a WCF web service from a web page, you have (at least) three options: Have the ASP.NET ScriptManager generate a strongly-typed JavaScript proxy to the service that you can call directly (you even get Visual Studio intellisense!)

Why use AJAX?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.


1 Answers

Here is a piece of working code.

Interface

[ServiceContract]
    public interface IDataService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
        List<RequestData> GetUser(RequestData data);

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "UsersList/{id}",RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
        RequestData UsersList(string id);



    }

Class implementing interface

public class DataService : IDataService
    {

        public List<RequestData> GetUser(RequestData data)
        {
            List<RequestData> list = new List<RequestData>();
            if (data.Name.ToUpper() == "MAIRAJ")
            {
                list.Add(new RequestData
                {
                    Name = "Mairaj",
                    Age = 25,
                    Address = "Test Address"
                });
                list.Add(new RequestData
                {
                    Name = "Ahmad",
                    Age = 25,
                    Address = "Test Address"
                });

            }
            return list;
        }
        public RequestData UsersList(string userId)
        {
                return new RequestData
                {
                    Name = "Mairaj",
                    Age = 25,
                    Address = "Test Address"
                };
         }

    }

Custom Class

As i am passing object of this class as parameter to method and returning object of this so i am using this. You may not need it.

[DataContract]
    public class RequestData
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int Age { get; set; }
        [DataMember]
        public string Address { get; set; }

    }

Web.Config

<configuration>
    <configSections>
    </configSections>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="EndpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="WCFWebApp.DataService">
        <endpoint address="" binding="webHttpBinding" contract="WCFWebApp.IDataService" behaviorConfiguration="EndpBehavior"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

And here is how you call it

var Data = {
        Name: "Mairaj",
        Age: 20,
        Address: "Test Address"
        //userId:1
    };
    $.ajax({
        type: "POST",
        url: "/DataService.svc/GetUser",
        dataType: "JSON",
        data: JSON.stringify(Data),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert("Data is " + data);
        },
        error: function () {
        }
    });

You need to change name of service classes in web.config and url in jquery code from where you will call it.

like image 168
Mairaj Ahmad Avatar answered Sep 30 '22 00:09

Mairaj Ahmad