calling asmx web service from jQuery - asp.net

I am not able to call web service(asmx) from jQuery function.
It is saying "access denied" error while calling web service. It is working in the dev and local machine but I am getting the same error.
Here is my ajax call
$.ajax({
type: "POST",
url: "http://server.com/calculator.asmx/calculus",
data: "{ 'userID': '" + $("#usrid").val() + "','password': '" + $("#password").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
My web service is
[WebService(Namespace = "http://www.company.com/webservices/calculus")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class calculator : System.Web.Services.WebService
{
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet=false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public bool calculus(string userName, string password)
{// my code}
The error is in http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js function and
the "Access denied" error at e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);
I have included [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] with the class as shown in http://forums.asp.net/p/1570168/3935094.aspx and not able to fix the prob. Can any one please help me regarding this.
Thank you

AJAX calls are bound to the same origin policy meaning that you cannot invoke a web service which is situated on a different domain. The browser will simply drop the request. One possible solution would be to write a server side script on the same domain which will serve as bridge to the actual web service and then call this script.

JSONP is a possible way to workaround the "same origin policy" (aka cross-site-scripting or XSS) limitations. It comes with its own set of challenges (for example, it works only with GET-mode requests), so it's certainly not a panacea. But it's probably worth your time to give it a look. There's a decent number of stackoverflow postings about it, which should help you get started.

Related

ASP.NET webservice responds with Internal Server Error (500) to post and get requests

The webservice code is simple:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void receiveOrder(string json) {
Context.Response.Write("ok");
}
And the jquery calling the webservice is as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50730/GingerWeb.asmx/receiveOrder',
data: 'test', //JSON.stringify(webOrder),
dataType: "text",
success: function(data){
if(data === "ok")
orderPlaced();
}
});
And yet the chrome console reads in provocative red:
500 (Internal Server Error)
The problem is that ASMX web-service need to find all input parameters in the request. If at least one input parameter will be not found in the request to the server the web service failed with the status code 500 (Internal Server Error).
The reason is that you send the data in the wrong way. The name of the input parameter of the web method is json (see void receiveOrder(string json)). So the data option of the $.ajax should be in the form
data: JSON.stringify({json: webOrder})
if you use type: "POST" instead of data: JSON.stringify(webOrder) which you tried before. In the case in the body of the POST request will be json=theVlue instead of just theValue.
If you would use type: "GET" the format of data parameter should be changed to
data: {json: JSON.stringify(webOrder)}
The value of the dataType should be 'json'. After the changes the $.ajax should work.
Moreover I would recommend you to use relative paths in the url option. I mean to use '/GingerWeb.asmx/receiveOrder' instead of 'http://localhost:50730/GingerWeb.asmx/receiveOrder'. It will save you from same origin policy errors.
Hello Oleg: Your explanation is simple and to the point. I had a similar problem which your explanation solved. I am providing code snippet to help 'searchers' understand what I was facing and how the above helped solve. In short I am issuing a simple jquery (.ajax) from a aspx page. I have created a webservice that gets some data from backend (cache/db) and return's the same in json format.
JS CODE:
var parameters = "{'pageName':'" + sPage + "'}"
var request = $.ajax({
type: "POST",
url: "/NotificationWebService.asmx/GetNotification",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
ASP.NET Code Behind for Web Service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetNotification(string pageName)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Notification ns = NotificationCache.GetActiveNotificationForPage(pageName);
if (ns != null)
{
NotificationJSData nJSData = new NotificationJSData();
nJSData.Code = ns.Code;
nJSData.displayFreq = (short)ns.DisplayFreq;
nJSData.expiryDate = ns.ToDateStr;
return js.Serialize(nJSData);
}
return null;
}
It is ABSOLUTELY necessary to ensure that you match 'pageName' variable name specified in web service code with what is sent in your data parameter of the ajax request. I had them different and changed it to be the same, after spending hours, I finally found the right solution, thanks to this post. Also, in my case I am only passing a single "name:value" pair so I didn't even have to use some json De-serialization function to get the value, pageName above gives me only the value.

JSON Web service with ASP.NET - from a frustrated php guy

I've been a PHP developer for a few years now and have developed at least a dozen APIs using JSON. Create a url that does a task, and return json_encode($array)... Piece of cake...right?
Now, I used to be a .net developer a while back (about 8 yrs ago) and I've been given the task to develop a small api/webservice for a client. I've been doing some reading on WCF and have been tinkering with it for a few hours now. My question is.. Is it me or is it incredibly over complicated to just run a RESTFUL query and return a block of JSON? In other words, why can't I just create an ASPX page that takes an array and encodes it as JSON and spits it out? Does it really HAVE to be WCF? Or even ASMX for that matter? Feels like overkill? No? Can someone offer a valid reson on why I need to go through the pain of WCF if I'm making a simple service that returns a few lines of JSON?
You can use WebMethods:
Using jQuery to directly call ASP.NET AJAX page methods
Code-behind:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Script:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// alert(msg.d);
}
});

Problem retrieving XML data from an ASP.NET Web service

I am trying to call a Web service to retrieve some XML data from a database. The Ajax call works fine if I use a static file e.g. like this:
$.ajax({
type: "GET",
url: "test2.xml",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
but fails when I try to call the Web service e.g. like this:
$.ajax({
type: "POST",
url: "Services/CheckOutService.svc/GetXMLData",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
The error I get 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."
The GetXMLData method looks like this:
// Interface
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetXMLData(XMLDataRequest request);
...
// Implementation
public string GetXMLData(XMLDataRequest request)
{
request.ShopperId = ShopperId;
return checkOutManager.GetXMLData(request);
}
The GetXMLData method has been configured to return XML and the Ajax call has its datatype set as XML so I'm very confused as to what is causing the error.
EDIT: If I alter the $.ajax() call slightly so that the contentType is specified I get this error:
The data at the root level is invalid.
Line 1, position 1.
I've tried contentType: "text/xml" and contentType: "application/xml" and both give the same error.
EDIT: Yesterday (Aug 30th) I noticed that the service call would succeed if I omitted the data parameter of the ajax call. I guess there is something about the JSON object that is causing a problem. For now I have implemented this functionality on the server side of the application but I do intend to revisit this when I get some time.
My first guess would be that the content type was wrong. What do you see when you look at the stream using Fiddler or similar?

Session State not Retained over calls to a Page Method

My server side code:
[WebMethod(CacheDuration = 0, EnableSession = true)]
public static int UserID()
{
if (HttpContext.Current.Session["UserID"] == null) return 0;
int UserID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
return (UserID);
}
My Client side code:
$.ajax({
type: "POST", cache: false,
url: "Login.aspx/UserID",
data: "{'r':" + rnd() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
This codes runs well on my localhost.
and the "UserID" ajax call, return the right value of the Session parameter.
but when i try to upload my website on the server, the "UserID" ajax call always returns false!!
my server is asp.net 2.0 and I'm using jquery 1.3.2
So please help to solve this problem.
Read this article: ASP.NET Session State FAQ
I found my answer in this questions:
Q: Session states works on some web servers but not on others.
A: Maybe machine name problem. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112 .
Q: Why are my Session variables lost frequently when using InProc mode?
A: Probably because of application recycle. See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316148
Changing sessionState mode to "StateServer" solved the problem.
Use code below:
<sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424"
cookieless="false"
timeout="999"/>
A few things to check :
Are you using WebFarm configuration? there might be a problem when using session in WebFarm configuration.
Have you check your network traffic using tools like Fiddler or FireBug? Is ASP.NET Auth cookie sent during AJAX call?
Can you confirm your session var is valid?

How to get URL Parameters from asp.net / jQuery.ajax POST?

I am trying to figure out how to get the parameters that are passed in the URL from a jQuery plugin that I am using. Basically, I'm sending a POST ajax request to my web service and trying to use the URL parameters, but they are always returned as nothing. I'm assuming this has to do with the fact that I'm in a POST.
Can anyone please provide some insight for me on how to accomplish this?
I'm unsure why you're choosing to use querystring parameters on an AJAX call. Unless there's a very specific reason, you should just post them as parameters to your web service method instead.
If you're using asp.net WebForms, I recommend using the ScriptManager to generate a javascript proxy to your web-service, and then use that javascript proxy instead of manually doing an ajax call. Here's a quick tutorial/walk-through on using ScriptManager with web services: http://msdn.microsoft.com/en-us/magazine/cc163354.aspx
Something roughly like this:
// in html you have this
<script src="WebService.asmx/jsdebug" type="text/javascript"></script>
// csharp web-service like this
[WebMethod]
public int Add(int a, int b) { return a + b; }
// further javascript to call it
function CallAdd()
{
// method will return immediately
// processing done asynchronously
WebService.Add(0,6, OnMethodSucceeded, OnMethodFailed);
}
This should eliminate the need to post parameters via query-string, which is typically not supported in a soap environment, as the service expects a well-formed soap message.
Hi I'm using the jQuery jqGrid plugin and by default it posts 5 or 6 parameters to the url. I was having trouble getting to those parameters and from looking at some of the php examples, it showed the method grabbing the parameters from the Form variables...I was just trying to see if there was a way I could do that. I'll see what I can do about posting them as parameters. . . just for giggles, is there a way that I would or could do this though?
I'm having a similar problem.
I'm using jQuery/json and POSTing back to a C#/Webservice. I don't know how to read the json variable I created.
Here's the client side(on a user control):
<script type="text/javascript" language="javascript">
function DoLogin()
{
var un = document.getElementById('UserNameText').value;
var pw = document.getElementById('PasswordText').value;
var info = "{ 'UserName':'" + un + "', 'Password':'" + pw + "'}";
$.ajax(
{
type: "POST",
url: "http://localhost:60876/Sitefinity/Services/Login/Login.asmx/LoginSpecial",
dataType: 'json',
data: info,
contentType: "application/json; charset=utf-8",
success: function (msg) { alert(msg.d); },
error: function (msg) { alert(msg.responseText); }
});
}
</script>
Here's the web service side:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Login : System.Web.Services.WebService
{
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string LoginSpecial()
{
// read the json variables: UserName, Password.
string un = HttpContext.Current.Request["UserName"] != null ? HttpContext.Current.Request["UserName"].ToString() : String.Empty;
// the previous isn't working for some reason.
return "Some message here";
}
}
I'm getting to the webservice but I need the Username/Password from json to do some validation.
for ASP.NET....
you can get the POST parameters with Request["paramName"];
If your using a GET request with query string parameters then
Request.QueryString["paramName"];
string parameter = HttpUtility.ParseQueryString(HttpContext.Current.Request.UrlReferrer.Query).Get("param1");

Resources