Skip to content Skip to sidebar Skip to footer

Why Can't I Access My Wcf Web Service With Javascript?

I'm new at AJAX and I'm trying to access a WCF web service the following way: $(function () { $('#formNew').submit(function () { var datos = { 'Nombre': $('

Solution 1:

The JSON.stringify(data) use is to convert a javascript object to json representation.

I think that in the success\error functions you need to go the other way:

success: function (data) {
                            alert("Exito " + JSON.parse(data));
                          },
 error:   function (data) {
                            alert("Error " + JSON.parse(data));
                          }

(when using JSON.parse, JSON.stringify - make sure you included the json2.min.js in your project)

Solution 2:

I normally use the following configuration to enable ajax calls to my WCF services:

1) First I create a JSON endpoint behaviour in Web.config and associate my service to it:

<system.serviceModel><behaviors><endpointBehaviors><behaviorname="WebHttpJson"><webHttpdefaultBodyStyle="Wrapped"defaultOutgoingResponseFormat="Json" /></behavior></endpointBehaviors></behaviors><services><servicename="MyApp.LoginService"><endpointaddress=""behaviorConfiguration="WebHttpJson"binding="webHttpBinding"contract="MyApp.LoginService" /></service></services></system.serviceModel>

2) Then I can simply define my WCF service like this:

[ServiceContract]
publicclassLoginService
{
    [OperationContract]
    publicvoidSignIn(string email, string pswd)
    {
        // Check credentials and create session cookie
    }
}

3) And finally make jQuery ajax calls like showed below:

$.ajax({
    contentType: 'application/json; charset=utf-8',
    url: serviceUrl + '/SignIn',
    type: 'POST',
    data: JSON.stringify({
        email: 'john.doe@abc.com', 
        pswd: 'qwerty'
    }),
    success: function () { alert('success!'); },
    error: function () { alert('error!'); }
});

Post a Comment for "Why Can't I Access My Wcf Web Service With Javascript?"