jQuery Ajax WCF POST - Return Boolean - javascript

I can't seem to find an example on how to post from jQuery to a WCF web service and capture the returned boolean. This is the code I have so far for returning JSON data:
Javascript
function VerifyPINData(pin) {
$.ajax({
type: 'POST',
url: "http://localhost:8523/WebService/VerifyPINData?pinData=" + pin,
data: JSON.stringify,
contentType: 'application/json; charset=utf-8',
success: function(data){ alert("result is: " + data); },
error: function() {alert("error"); },
complete: function() { alert("complete"); }
});
}
WCF
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "VerifyPINData?pinData={pinData}")]
bool VerifyPINData(string pinData);
Any help would be appreciated.

Figured it out:
Casted the data returned as a boolean:
success: function(data){ alert("result is: " + Boolean(data)); },
Specified the response as JSON in WCF
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "VerifyPINData?pinData={pinData}", ResponseFormat = WebMessageFormat.Json)]
bool VerifyPINData(string pinData);

Related

WCF service POST method not working

i am getting following error when i call the wcf service using ajax from another project :
The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details.
i have created the following wcf service in a project :
IService1.cs -
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
int AddNumbers(int a);
[OperationContract]
string ShowMsg();
// TODO: Add your service operations here
}
service1.cs -
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public int AddNumbers(int a)
{
return a + 5;
}
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public string ShowMsg()
{
return "Hello World!";
}
}
and this is how i am consuming it from another project :
$.ajax({
type: "POST",
url: "http://localhost:16748/Service1.svc/AddNumbers",
contenType: 'application/json',
data: JSON.stringify({ a: 4 }),
dataType: 'json',
success: function (data) {
$("#elementsDiv").html(data);
},
error: function (xhr, status, error) {
var err = xhr.responseText;
$("#elementsDiv").html(err);
}
});
can anybody help me with this?
I believe you may have a typo in your ajax call:
contenType: 'application/json',
I think this should be:
contentType: 'application/json',
other than that your code runs fine for me.

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:
And On Console:
EDIT1:
When i change contenttyp to :appplication/json;charset=utf-8
http://api.jquery.com/jquery.ajax/
crossDomain point in doc
Check it, u send cross domain ajax. It's not allowed by default.
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: "abc#xyz.com",
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);
}
});

Jquery Ajax POST Request sending data issue

I have searched a lot and not been able to find a working solution to why my post request is not sending it's data to the server. I can send the request without data and I get my results from the server, but I just cannot send my data to the server. I have narrowed it down to the "data" attribute and assume I am just doing something wrong. Thank you.
Client
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: "{}", //works (to return a result)
//data: "{sendData: '" + dataPackage + "'}", //does not work
//data: dataPackage, //does not work
//data: { sendData: dataPackage }, //does not work
//data: { "sendData": dataPackage }, //does not work
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
Server
[WebMethod]
public static string SaveItem(string sendData)
{
string result = "received: " + sendData;
return result;
}
Please help, I just cant seem to get it working and know it has got to be a syntax issue...
Similar problems I have found (but no working answers):
https://stackoverflow.com/questions/7258933/jquery-ajax-data-parameter-syntax
https://stackoverflow.com/questions/7262940/webmethod-not-being-called?lq=1
Try this one:
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: $.toJSON({ sendData: dataPackage }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
The toJSON will convert your JS object into a proper JSON string. You could also use JSON.stringify
Try this:
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: {sendData: "string to send" }
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});

How to set Array String through JS Post Back to Web Method?

How to send array strings with JS post back to Web Method in ASP.NET, code sample is below:
function service() {
var items = $('#jqxTree').jqxTree('getCheckedItems');
// var jsonText = JSON.stringify({ list: items });
myData = {};
for (index in items) {
myData[index] = items[index].label;
}
$.ajax({
type: "POST",
url: "ServiceConfiguration.aspx/ProcessIndexes",
data: "{'jsonValue': " + JSON.stringify(myData) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (msg) {
}
});
//alert(items);
}
now i am trying with following:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void ProcessIndexes(List<string> jsonValue)
{
var serializer = new JavaScriptSerializer();
}
Been awhile since I've been in .NET land, but something like this should work:
$.ajax({
type: "POST",
url: "SomeForm.aspx/SomeWebMethod",
data: JSON.stringify({ someValues: ["foo", "bar"] }),
contentType: "application/json",
dataType: "json",
success: function(resp) {
// handle success here
},
error: function() {
// handle error here
}
});

$.ajax - send object for data property

I'm trying to call an asmx web service method with jQuery and pass an actual JavaScript object for the data, and get JSON back. The closest I can come is this:
$.ajax({
url: "WebService.asmx/HelloWorld",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ num: 12, name: "Adam" }),
dataType: "json",
success: function (data) { alert(data.d); }
});
How can I successfully make this call without first stringifying my object?
I tried this (removing the contentType)
$.ajax({
url: "WebService.asmx/HelloWorld",
type: "POST",
data: { num: 12, name: "Adam" },
dataType: "json",
success: function (data) { alert(data.d); }
});
But that returns the result in XML, not json.
Here's the web method:
[WebMethod]
[ScriptMethod]
public string HelloWorld(int num, string name) {
return ++num + name;
}
EDIT
Here's a screenshot of the headers of the request. Clearly content-type is set to xml for the response.
Set the ResponseFormat:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(int num, string name) {
return ++num + name;
}
Just a NOTE: asmx doesn't return JSON for GETs only POST
Per Dave's Comments
It is impossible with the ASMX and ASPX JSON endpoints. They require the application/json Content-Type and a POST request or no JSON.

Categories