C Sharper
C Sharper

Reputation: 8646

Calling webservice method through ajax

I have WCF service method:

[WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
[OperationContract]
bool validateLogin(Login objLogin);

I am calling this method through my phonegap code ajax as:

var parameters = {
    "EmailID": EmailID,
    "Password": Password
};

$.ajax({
    url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
    data: JSON.stringify(parameters),
    contentType: "text/xml;charset=utf-8",
    dataType: "json",
    headers: { 
        SOAPAction: '' 
    }, 
    type: 'POST',   
    processdata: false,
    cache: false,
    success: function (Data) {
        alert("asdsad");
    },
    error: function (response) {
        var value = JSON.stringify(response);
        alert("Error in Saving.Please try later."+value);
    }
});

But service method is not getting called.

On Network tab it gives me error:

enter image description here

And On Console:

enter image description here

EDIT1:

When i change contenttyp to :appplication/json;charset=utf-8

enter image description here

Upvotes: 0

Views: 517

Answers (2)

Jankya
Jankya

Reputation: 958

Most probably because of Parameters which you are passing and return type of WCF service. The method should return Object instead of bool. The .Net framework will convert the returned object to the JSON string automatically for you.

Service Side :

    [WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
    [OperationContract]
    Object validateLogin(String Email, String Password)
        {
           //Do your stuff return bool value
        }

AJAX Call :

$.ajax({
    url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
    data: function ( {
              return JSON.stringify({
                Email: "[email protected]",
                Password: "XXXXXXXXXX"
               });
             },
    contentType: "text/xml;charset=utf-8",
    dataType: "json",
    headers: { 
        SOAPAction: '' 
    }, 
    type: 'POST',   
    processdata: false,
    cache: false,
    success: function (Data) {
        alert("asdsad");
    },
    error: function (response) {
        var value = JSON.stringify(response);
        alert("Error in Saving.Please try later."+value);
    }
});

Upvotes: 1

awMinor
awMinor

Reputation: 173

http://api.jquery.com/jquery.ajax/

crossDomain point in doc

Check it, u send cross domain ajax. It's not allowed by default.

Upvotes: 1

Related Questions