Priyan Perera
Priyan Perera

Reputation: 560

Calling WCF service from jquery Ajax

I am trying to create a WCF service and call its methods using jquery AJAX. So far I have not being able to figure out how to do it. I have read some of the solutions given in SO but still unable to fix it. Any help would be appreciated. I have the following code.

In WCF service.

Service Contract

[ServiceContract]
public interface IDatingService
{
[WebInvoke(Method = "POST",
RequestFormat= WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "/AddUser")]
    [OperationContract]
    User AddUser(User user);
}

Implementation

public User AddUser(User user)
{
    return userRepository.Add(user);
}

The configuration

<system.serviceModel>
 <behaviors>
  <serviceBehaviors>
    <behavior name="DatingServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="DatingServiceBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="DatingServiceBehavior"
           name="DatingService.Service.DatingService">
    <endpoint address="" binding="webHttpBinding"
       contract="DatingService.Service.IDatingService"
       behaviorConfiguration="DatingServiceBehavior"/>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
 </services>
</system.serviceModel>

From the client side, I use the following code to call the service.

saveInfo: function () {
    console.log('saveInfo');
    if ($('#terms-check').is(":checked")) {
        if (app.validateEmail()) {
            var input =
                {
                    "user":
                    {
                        "LoginId": user.LoginId.text(),
                        "Password": user.Password.text(),
                        "Email": user.Email.val()
                    }
                };
            $.ajax({
                type: "POST",
                url: "http://localhost:36908/DatingService.svc/AddUser",
                data: JSON.stringify(input),
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: app.onSaveSuccess,
                error: app.onSaveError
            });
        }
        else {
            $('.error-label').text('Invalid email address.');
        }
    }
    else {
        $('.error-label').text('Please check the terms and conditions.');
    }
}

When I call the service, I am getting Bad Request.

Upvotes: 5

Views: 15407

Answers (2)

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4608

You should construct objects like this.You are getting 400 Bad request because the wcf expects data in a format which ajax is not sending.

var obj = {};
obj.LoginId = user.LoginId.text();
obj.Password = user.Password.text();
obj.Email =  user.Email.val();

var jsonObj=JSON.stringify(obj);
var dataToSend = '{"user":'+jsonObj+'}';

Then change your data part in ajax query

       $.ajax({
                type: "POST",
                url: "http://localhost:36908/DatingService.svc/AddUser",
                data: JSON.stringify({user:obj}),
    or
                data: dataToSend,
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: app.onSaveSuccess,
                error: app.onSaveError
            });

Upvotes: 0

MSUH
MSUH

Reputation: 872

Issue can be related to "localhost:36908", you need to make sure your service is started and hosted on same port, you can go to WCF project properties and select "Use Visual studio developer server", check on "Specific Port" option and write 36908 in it, then start development server or debug start the solution, Try hitting the url again.

Upvotes: 1

Related Questions