3 mistakes to avoid when using jQuery with ASP.NET AJAX
AJAX, ASP.NET, JavaScript, jQuery By Dave Ward. Updated June 3, 2010Note: This post is part of a long-running series of posts covering the union of jQuery and ASP.NET: jQuery for the ASP.NET Developer.
Topics in this series range all the way from using jQuery to enhance UpdatePanels to using jQuery up to completely manage rendering and interaction in the browser with ASP.NET only acting as a backend API. If the post you're viewing now is something that interests you, be sure to check out the rest of the posts in this series.
Over the past few weeks, I think I have definitely embodied Jeff Atwood‘s claim that we’re all amateurs, learning together. Despite my best efforts to thoroughly test before posting, a few problems slipped through in my recent posts about using jQuery to consume ASP.NET JSON serialized web services and using jQuery to call ASP.NET AJAX page methods.
On the bright side, your great feedback in both posts’ comments has reinforced the fact that some of the best content on my blog is the part that you write.
In this post, I’m going to detail three of the problems that were discovered as a result of those previous two posts:
- An extra requirement when making a read-only request to IIS6+.
- An oddity in Internet Explorer 7′s XmlHttpRequest class.
- A common mistake when passing JSON parameters through jQuery.
Finally, I’ll suggest what I now believe to be a best practice usage, taking all of these issues into account.
Security requirements when POSTing to IIS
This error message was the most common problem that was reported:
Length Required
The underlying issue is that most installations of IIS6+ require a content-length be provided with all POST requests, even if there is no content (POST data).
The content-length for a request with no data should be 0, but jQuery doesn’t set that header automatically unless there is a data parameter. Since ASP.NET AJAX’s JSON serialized services require a POST request, this becomes a stumbling block for read-only requests.
The easiest way I’ve found to work around this is to use an empty JSON object as a parameter on read-only requests. For example, if you were calling a page method:
$.ajax({ type: "POST", url: "PageMethod.aspx/PageMethodName", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json" });
This will cause jQuery to correctly set a content-length of 2, while your web service or page method will happily ignore the empty parameter and treat the request as read-only.
You might notice the content-type is set differently in this example than in my previous posts. More on that next:
A problem with Internet Explorer and XmlHttpRequest
Previously, to call ASP.NET AJAX services with jQuery, I suggested this usage:
$.ajax({ type: "POST", url: "WebService.asmx/WebMethodName", beforeSend: function(xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); }, dataType: "json" });
The reason for the beforeSend delegate is due a quirk in jQuery which causes it to send a specified content-type only if there is also a data parameter specified.
For security reasons, ASP.NET AJAX will not provide a JSON serialized response unless the proper content-type is provided. By using the beforeSend delegate as shown, the content-type will be manually set on the XmlHttpRequest object, before the request.
However, the new XmlHttpRequest class in Internet Explorer 7 doesn’t implement setRequestHeader very intuitively. Instead of setting the specified header, it appends the value.
This becomes a problem when you make a request that includes a data parameter. When POST data is provided, jQuery will automatically set the content-type to its default of application/x-www-form-urlencoded. In the beforeSend delegate, the required application/json; charset=utf-8 will be appended after jQuery’s default.
End result? Because this amalgamation of content-types isn’t what ASP.NET AJAX expects, the web service will not return JSON serialized content and jQuery will be unable to parse it.
Solution? If you’re sending data in your request, use jQuery’s contentType parameter to set the content-type, so that the default is never added:
$.ajax({ type: "POST", url: "WebService.asmx/WebMethodName", data: "{'fname':'dave', 'lname':'ward'}", contentType: "application/json; charset=utf-8", dataType: "json" });
JSON, objects, and strings: oh my!
ASP.NET AJAX script services and page methods understand and expect input parameters to be serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.
However, if you directly provide a JSON object as the data parameter for an $.ajax call, jQuery will attempt to URL encode the object instead of passing it on to your web service.
Take this sample request, for example:
$.ajax({ type: "POST", url: "WebService.asmx/WebMethodName", data: {'fname':'dave', 'lname':'ward'}, contentType: "application/json; charset=utf-8", dataType: "json" });
Because that data parameter is a valid object literal, calling the web service this way won’t throw any JavaScript errors on the client-side. Unfortunately, it won’t have the desired result either. Instead of passing that object through to the web service as JSON, jQuery will automatically URL encode it and send it as:
fname=dave&lname=ward
To which, the server will respond with:
Invalid JSON primitive: fname.
This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter, like this:
$.ajax({ type: "POST", url: "WebService.asmx/WebMethodName", data: "{'fname':'dave', 'lname':'ward'}", contentType: "application/json; charset=utf-8", dataType: "json" });
It’s a small change in syntax, but makes all the difference. Now, jQuery will leave our JSON object alone and pass the entire string to ASP.NET for parsing on the server side.
Best practice? I hope so this time!
Taking these three caveats into account, I think this is the best practice for calling read-only ASP.NET AJAX web services via jQuery:
$.ajax({ type: "POST", url: "ServiceName.asmx/WebMethodName", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do interesting things here. } });
When consuming web services that require parameters, the usage is similar. Just make sure that you’re passing a JSON object in a string:
$.ajax({ type: "POST", url: "ServiceName.asmx/WebMethodName", data: "{'fname':'dave','lname':'ward'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do magic here. } });
In either of these cases, substitute PageName.aspx for ServiceName.asmx and PageMethodName for WebMethodName if you want to call a page method instead of a web service.
Conclusion
I hope this post will help you to avoid these common problems when using jQuery with ASP.NET AJAX. I think there’s a great synergy between the two that is certainly worth jumping through these few hoops.
I’d especially like to thank Martin and Ryan for their invaluable feedback, leading to two of the three solutions posted above.
If you’ve run into related problems yourself, I’m eager to hear about them. Please don’t hesitate to comment if you think I’m still missing something important.
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
27 Mentions Elsewhere
- Dew Drop – June 5, 2008 | Alvin Ashcraft's Morning Dew
- Interesting Finds: 2008.06.06 - gOODiDEA.NET
- 3 mistakes to avoid when using jQuery with ASP.NET AJAX
- Pathfinder Development » Pitfalls of Using JQuery with ASP.NET Ajax
- Jamie Thompson » Tips for Using JQuery with ASP.NET Ajax
- Wöchentliche Rundablage: Silverlight 2, WPF, ASP.NET MVC, jQuery… | Code-Inside Blog
- Weekly Links: Silverlight 2, WPF, ASP.NET MVC, jQuery… | Code-Inside Blog International
- More jQuery with Ajax/Json : { null != Steve }
- Playground Sunshine » Blog Archive » jQuery Flexigrid with ASP.NET webservice and ADO.NET Entity Framework Part 1
- Good links: ASP .NET and JQuery - Programmatically Speaking ...
- Using jQuery to Consume ASP.NET 2.0 « vincenthome’s Tech Clips
- Submitting an AJAX Form with ASP.NET MVC + jQuery « {Programming} & Life
- jQuery and ASP .NET MVC: browser issues | peterskim
- jQuery autocomplete plugin with ASMX web service and JSON « Adam Mokan's Development Blog
- Building an AJAX web part with jQuery (Part 2)
- My Tech World » Ajax Gotchas with jQuery and ASP.Net MVC
- uberVU - social comments
- Developit » Using jQuery to Insert a New Database Record
- WCF and JSON « Wibber's Blog
- ASP.Net Web Service with JSON Formatted Response « Brad's Blog
- ASP.NET und JQuery Serialization « Schädler und .NET
- Bridging ASP.NET & jQuery | Dogma/Geek Bridging ASP.NET & jQuery | Outlet for my techno babble.
- Pitfalls of Using JQuery with ASP.NET Ajax | Pathfinder Software
- A quick guide to have jQuery call your ASP.NET PageMethods « I Came, I Learned, I Blogged
- [WebMethod]‘s and jQuery « Mike#
- My Big Ol’ JSON Rest mistake | Jack's Sleazy Hacks
- 首页Jquery的Autocomplete实现类似Skype网站功能 | ☆諸紳の煌殙☆s‘零℃空间



Thanks for the clarification, it will save a lot of time for people just trying to figure it out for the first time. I was keeping the ScriptManager on my pages solely for the ability to call PageMethods and now I’m able to remove it completely.
Any advice on the best way to send and receive objects?
For serializing and deserializing objects on the client side, check out the JSON2 library.
Dave, thanks for the article, it’s very useful to see those 3 items listed on one page. I’m in the process of using jQuery and asp.net web services after reading your previous post on why the update panel is dangerous.
Thanks Dave. It was the third case you documented (string formatting) that caused me real problems for a while, eventually I figured it out but it wasn’t obvious!
Calling web services from jQuery instead of having to use the full ASP.NET Ajax libraries is a great option.
Great stuff, although i have a problem.
I am injecting Json to my CMS, i do rewrite urls.
since some of the stuff i want to do with the ajax call i related to the page itself. i sent lets say pagename.html/get_date which gets rewrited to page.aspx?id=100&/get_date.
doing it this way i do get a response with the page content, not the webmethod return.
any hints on how i could access the pagemethod??
i am in net 2.0
Also messing around with both, my cms and the article code. i seemed not able to call the div from a Webpart.
yes let complicated a bit!!!!.
Thanks from your help in adavance
In that case, I would suggest using a separate web service, and make sure *.asmx is excluded from the URL rewriting.
Thanks, Dave.
i wonder about that approach, but i still can see how could i used the page data from the service, since the webservice is not page-context-aware.
my problem comes when in a webparts portal enviorement i try to call a webpart method from a page so i need that page to load in order to get the properties-webpart-centric-data to interact with the method.
i a way i just want to get away from update panel altogether and use jquery-json to do all the work for me.
the webservice approach i could use to the drag-and-drop functionlity,keeping the new order in memory until the page is requested again.
i keep researching, will post some code when done.
thanks
Great post Dave! I want to thank you for putting in so much leg work under using jQuery as an alternative to or along side ASP.NET Ajax. Keep up the good work.
Awesome follow-up Dave. Between your posts and Rick Strahl’s I’ve been motivated to use jQuery whenever possible and avoid the huge overhead of the MSAJAX library/toolkit — with the side benefit of being able to use these same techniques for my PHP clients as well.
Thank you for the awesome info!!! I am in the process of refactoring much of my code with the goal of eliminating ScriptManager, and am quite excited about it.
One additional requirement that I had was that some of my web service methods return a DataSet object (for use in Ext-JS grids), and when ASP.NET serializes a DataSet to JSON, it encodes the date as a string in the format “Date( 02348293482 )” (or similar), which did not evaluate properly.
To fix this, I extended the jQuery httpData() method to replace those dates with text that will, when evaluated, result in an actual Javascript Date object, like so:
Anyhow, thanks again for the wonderful info, it’s been incredibly helpful!!!
DOH! I just now realized that using a prefilter function is already provided for, and would be better than extending the httpData method… As you say, we are amateurs learning together, haha. Well, I am sure you get the idea :)
And the biggest mistake of all. Mixing ASP.NET AJAX with jQuery! :) Seriously I’ve given up on ASP.NET AJAX, the other AJAX Libraries like jQuery offer better performance. Why not cut out ASP.NET AJAX altogether?
That’s essentially the point of this. You can substitute jQuery for the ASP.NET AJAX client framework this way, if you aren’t using UpdatePanels or toolkit extenders.
There’s no reason to avoid ASP.NET AJAX on the server side though. Letting it handle JSON serializing your services is just one less thing you have to worry about. Being able to write page methods is handy too.
Right… I’m using WCF services that expose JSON, but the page methods look handy.
Hello Dave,
Good post, especially that I fall in some of those mistakes like length required and Internet explorer XmlHttpRequest problem when I first produced my on demand loading sample using jQuery.Ajax.
Thank you for the tips
What about calling .ashx handlers using JQuery , i think it is lightweight and flexible than Page Methods.
I don’t think there’d be much difference in performance there.
I’d definitely be interested in seeing some testing between those two. IAsyncCallback too, for that matter.
I’m in total agreement here with Rashed. I’ve been using ASHX handlers and have not looked back. If you examine the call stack compared with MVC etc and all these frameworky layery solutions, there’s no comparison. Less is more dude. Seriously.
I actually went back and tested this, not too long ago.
I found that my development machine took an average of ~2,800 milliseconds to handle 1,000 JSON-serialized HelloWorld requests. An ASHX handler doing the same work averaged ~2,400 milliseconds for the same 1,000 iterations. So the HttpHandler was faster, as expected, but the difference was literally a fraction of a millisecond per request.
I can see trimming that overhead being a worthwhile endeavor in the heaviest of heavy load environments, but I think it’s premature optimization at the cost of productivity in 99.9% of scenarios. Dealing with the JSON parsing and serialization when I don’t have to isn’t worth .4 milliseconds to me.
Actually, Dave, that’s great that you did that work and its fairly obvious you are right about the benchmarks. Concerning productivity though I disagree based on what I’m doing. For you, it maybe perfect. I’m not using MVC or Web forms. I use jQuery and straight razor i guess you call it web pages and we do this on high traffic ecommerce sites like Dragon Alliance for example and Olukai.com . Its more about not having to have a framework that I find productive probably coming from the reverse side of things. I don’t want to have to have MVC layers to dictate routes using file system or not, I just use URL Rewrite and JSON output etc. I agree with you though if you are doing MVC and other things like that requiring layers etc already then you are 100% correct sir. For me, its less productive though. To each his own sir and the world is better for it.
sorry one last thing, we do use json serialization from .NET directly its just not needing anything more than that. I don’t think this is really an argument rather than a preference. I just like typing less although my post here doesn’t suggest it. :)
You might be thinking of something different than what this post is about. This isn’t about MVC or its routing at all.
It’s about laying a foundation for using plain HTML rendered out of WebForms, sans WebControls, and jQuery talking to these ASMX/ASPX JSON endpoints that avoid the framework overhead in other areas of WebForms and/or MVC. So, the main difference is whether you want to type:
Or:
To produce the same result (the latter automatically handles JSON serialization and setting the correct content-type). The verbosity of the ASHX approach is a tough sell for .4 milliseconds, IMO.
You’re right though. To each his own. If it’s working for you, there’s nothing wrong with that. Just wanted to make sure we were talking about the same thing here.
hey,
is there any way to make “GET” work like this as well? i’ve been trying all morning but just get parsererror.
i can get it work with a readonly query but not with data parameters.
cheers.
If you’re using it with ASP.NET AJAX, the request has to be a POST, for security reasons.
you can use httpget=true in the scriptmethod attribute on a webmethod. just can’t seem to pass parameters to it….i guess you don’t really need it.
This was all working great for me, until today :(
Unfortunately, it all seems to fall down under Firefox 3, and I am having one heck of a time trying to find out why :(
(PS: Sorry about the double-post on the older blog entry, I was having trouble finding the correct one)
That’s odd. The code I posted still works for me in FireFox 3 (most of my original development and testing for these posts was done in FF3 betas too).
Are you getting an error at all? Try watching the request and response in FireBug.
No, I’m not getting any errors, and FireBug gives me absolutely nothing… No request headers, no response (headers or data), nothing. When I debug, the ReadyStateChanged event is fired with a status code of 0. FF 2 continues to work fine, as do Safari, Opera, and IE.
Obviously it’s time to extract this piece into a smaller repro case, cause I’m finding it hard to debug in the context of the larger application :(
Sometimes I wish I could go back and delete my comments, they are so embarrassing, haha.
After hours of searching, and reducing the problem to it’s very simplest components, and testing every permutation I could think of, I finally found the problem: Firebug itself, possibly in conjunction with (or because of) Aptana debugging extensions.
I had recently tried to start using Aptana Studio, and it required me to revert to an older (Aptana-customized) version of Firebug as well as add another Aptana-specific Firefox add-on, and apparently they are not fully compatible with FF3.
After removing those and “upgrading” Firebug to the latest version, everything is back to normal.
So let me apologize for wasting your time and to take this opportunity to thank you once again for the great info in the article!
@Takuan
No apologies needed here. I’m happy to know about this issue, now I don’t have to encounter it myself.
Thanks! :)
Firstly, thanks Dave after reading your original post on this subject, I’ve stopped using Script Manager and the ASP.NET AJAX framework completely.
I have since written a very simple function that replaces the jQuery ajax call. The function embodies each of the issues you raise in this post and supports GET & POST requests to both (JSON Enabled ASP.NET) Page Methods & Web Services.
An example of a call to the Page Method or Web Service is below.
Details can be found here: Briding ASP.NET & jQuery.
Great post – all common ‘gotchas’ – thanks!
I’m using jQuery with asp.net mvc – it’s magnificent :)
Hi Dave, what would be the easiest way to allow this to work cross-site (call a service from another site)?
I know it’s possible with JSONP, and that JQuery can handle JSONP.
What’s not clear is if there is any way in the 3.5 framework to easily implement it on the server.
Great articles by the way.
Best regards,
Lee
Hi, Lee.
As far as I know, there aren’t any built-in methods for generating JSONP. It shouldn’t be very difficult to roll your own though, using JavaScriptObjectSerializer.
Question. Does this work in ASP.NET 2.0 apps? I seem to have everythng working fine in the 3.5 apps I am using this in, but can’t seem to call a PageMethod in my 2.0 apps. Also I am using vb.net. Not sure if there are differences there either.
Thanks for the great post. I am having some trouble getting it to work in VN.NET though. And can’t fing an example of calling a page method with JQuery in VB.NET
I don’t think my problem is with .NET 2.0 since I have ASP.NET AJAX 1.0 installed. The problem seems to be trying to call a VB.NET Page Method because it works fine for me in C#. I must be missing something…
Imports System
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Partial Class vbTest
Inherits System.Web.UI.Page
Public Function GetDate() As String
Return DateTime.Now.ToString()
End Function
End Class
This is what I have trying to reproduce the C# date example from the post in VB.NET. Any help would be greatly appreciated.
Thanks,
-Adam
Hi Adam,
You need to decorate your PageMethod with the
<WebMethod()>attribute to expose it as a web service.Rich
Hi,
I’ve created a jQuery plugin for easy communication with ASP.NET Ajax enabled Web Services and PageMethods.
Details can be found here.
Rich
Check out http://schotime.net/jMsAjax.aspx for a fully functional jQuery plugin (jMsAjax) that requires no external libraries except for jQuery.
It also passes Dates in and out of web methods and services.
Guys, I love all the work you’re doing here and love not using AJAX.NET. I’m having a problem in a specific situation, that I haven’t seen addressed anywhere. It’s easy to send one parameter of data and get a nice JSON back from the .NET Web Service, but I can’t pass a complex JSON object to a service. I think my problem is on the .NET side and not the JavaScript side. No matter the format I use in my webmethod, I get a “is not supported for deserialization of an array” error.
I want to pass an object (simple structure, about 60 name/value pairs, none nested, no dates) How do I write the method to do this? I don’t care what datastructure it ends up in, I just need to be able to go through it piece by piece and do something with it.
Right now, it’s this simple, and still won’t run:
[WebMethod]
public string setBMB(string result)
{
return result;
}
Any ideas?
Hi Namlet,
The magic is in the __type attribute of the JSON object you send. You must add an attribute called __type to the object you send back to the web service or WCF end point. For ASMX web services the attribute simply contains the name of the class on the server (i.e.
person.__type = "Person"). For WCF you add:#to the end (i.e.person.__type = "Person:#").I have created example projects demonstrating this (for both ASMX web services and WCF), you can download them here.
I decided to save some CPU time and instead of calling [WebMethod] to call my handler. whic simply writes back to response JSON fomratted text…
For whatever reason it does not work with IE. Weird thing is that it works if i am debuggins application, or if i am using the Fiddler. If i am not doing one of either and simply hitting refresh the POST request from JQuery comes back with an error.
No problem with FireFox…
Hi George,
Are you able to post the server side code that generates the JSON and an example of the output? Also, your JavaScript call would be useful.
However, the fact that you have no problem with Firefox suggests to me that you should be looking at
the contentType of the jQuery call. Debugging and Fiddler (at a stretch) maybe messing with the encoding.
Is the CPU saving significant?
Rich
Thanks Richard for the try..
I finally figured out where problem is (or should I say was).
The difference between [WebMethod] and .ashx handler is that [WebMethod] never ignores input and always reads it completely.
The input stream must be read completely even if you are not interested in it.
So following code to my handler fixed the problem.
System.IO.Stream st = context.Request.InputStream;
byte []buf = new byte[100];
while (true)
{
int iRead = st.Read(buf, 0, 100);
if( iRead == 0 )
break;
}
st.Close();
Without that IE’s XMLHttpRequest can not properly read the output.
Not sure why IE’s XMLHttpRequest object is being such a “girl”.
FireFox’s XMLHttpRequest had no problem with it.
Oooofff. 2 days down the drain…..
Obviously you need to do this code if you are not interested in input and since I was following advice in this article and always passing ‘{}’ as a data I were not reading InputStream.
I’ve a question for you:
$.ajaxSetup
({
url: pagePath + “/” + fn,
type: “POST”,
contentType: “application/json; charset=utf-8″,
dataType: “json”,
data: “{“a”:”112″,”b”:”0,0,0,0,0,0,0,0,0,0,0″}”,
timeout: 30000
});
$.ajax
({
success: successFn,
error: errorFn
});
If i pass to “data” this string:
“{“a”:”112″,”b”:”0,0,0,0,0,0,0,0,0,0,0″}”
Where “b” in my PageMethod is an int[], i’ve this error:
“Cannot convert object of type ‘System.String’ to type ‘System.Int32[]‘”
Can anyone post an example where using jquery/asp.net and a PageMethod with an array parameter?
Thank u for your work.
tranky
If you change this
to this
you should stop receiving that error message.
Rich
thank u rich.
I’ve correct my code and now all is right.
THANK U SO MUCH!
For me Encosia in this moment is the best place for an asp.net developer.
cu.
I have a problem with jQuery.serializeArray(); the jQuery docs says that it serializes as JSON, however firebug shows is as simple querystring.
Any idea why is not real JSON?
Thanks
If you pass $.ajax() a JSON object for “data”, it will serialize it as a querystring (see the third “mistake” in the post).
I haven’t tested this myself, but try adding a “processData: false” to your $.ajax() call’s parameters.
I set the processData:false, but i get an error:
s.data.match is not a function
jQuery.readyList.push(function(){return ….url,s.async,s.username,s.password);else
Hi Dave,
I have doubt reg. security while stating the url, which includes webservice and webmethod as well. If I want to use webservice for authentication, user will be able to see complete uri the the HTML Source.
Thanks,
Sundeep.
You can always see the authentication URL in the HTML source for a page with a login form, whether using a web service, full postback, or the UpdatePanel’s partial postback.
That’s nothing to worry about.
Dave,
Great post – thanks for the info!
Thank you so much! Beautiful solutions. I’ll just add one novice mistake that cost me a half a day. (though probably everyone else knows it except me). And that is this: It helps to pay attention to where in the directory your request is coming from.
Sometimes this works:
url: “PageMethod.aspx/PageMethodName”,
While other times you need:
url: “../PageMethod.aspx/PageMethodName”,
Anyways, thanks for your great line of AJAX/asp.net articles!
The 4th mistake to avoid when using jQuery with ASP.NET AJAX:
jQuery.data() + UpdatePanel = Memory Leak
Hi there,
This is good stuff. Thank you. Has anyone modified the JavaScriptObjectSerializer to remove the “d object” wrapper?
I want to use some client code off-the-shelf but it won’t accept the wrapper.
Perhaps I could overide a method in the JavaScriptObjectSerializer to achieve this?
Thanks!
To my knowledge, you cannot easily remove the .d. See this later post for a more in-depth explanation of the .d: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
For your situation, I’d say either go with a WCF service or an HttpHandler to have complete control over what’s returned.
Hi Dave,
Thanks for your reply. They’re good suggestions. In the end I have managed to make a minor change to the client component along the lines of
data = data.d;
Thanks again.
Regards
Great articles, thank you.
I was pulling my hair out for last few hours trying to figure out the difference between calling a web service and page method. Other than having the method be static/shared, if you are calling a no param web method you need to include the data:”{}” whereas if you are calling a Web Service it doesn’t seem to mind if you have empty data or braces. Not such a biggy since most calls will usually pass parameters. In my case things weren’t working so I dumbed down the entire call and then this bit me.
Thanks again,
Rob Lingstuyl
Once again I found an answer on your site after hours of frustration. Thanks a lot, Dave.
Just wanted to mention that when enclosing string parameters in single quotes, it may be necessary to handle a case when a string contains a single quote. To do this, call replace(“‘”, “\\’”) on the string value [notice double back slash], e.g.:
Great article that aggregates fixes to all the various jQuery memory leaks dealing with UpdatePanel refreshes at http://www.quattrosource.com/2009/07/fixing-jquery-memory-leaks-in-asp-net/
Hi, Dave
This article is so great and helpful. I am new one for jquery. I did follow your example to use an empty JSON object as a parameter on read-only requests. It worked perfectly in my dev machine, however after deploying to server, the argumentoutofrange exception (parameter: length) will be thrown. any ideas? thanks in advance
Make sure that the empty JSON object is quoted (e.g. “{}”), otherwise jQuery will interfere by serializing it as k=v pairs (which will be blank in this case).
Other than that, are you sure it isn’t an unrelated issue in the server-side code? Is it returning a 500 error? If so, take a look at the stack trace in something like Firebug when it comes back.
Thanks a lot for your reply. Yes, it returns a 500 error and the stack trace says something wrong in system substring function. But my webmethod is just used to check whether some specific session value exists and return a boolean. i added a try-catch block in case some unexpected things happen. also used firebug for debugging but did not find anything. Did i miss something? Cheers
Hi, Dave
I met another problem recently. I use jquery to call pagemethod without arguments. It works OK under IIS5 + WindowsXP + VS2008. But after deployed to server (IIS7 + Windows7 + VS2008), jquery cannot hit the pagemethod and be directed to error function with server error 500
error: function(xhr, status, error) { // Display a generic error for now. alert("AJAX Error!"); }.
Any ideas about it? Much appreciate.
When you see a 500 error returned, that just means some server-side error was thrown in the page method’s code, not usually specific to jQuery or the AJAX call. If it hadn’t been an asynchronous call that caused the error, it would have shown you the yellow error screen you’re probably more used to.
Take a look at the stack trace in Firebug for details of what threw the error.
Hi Dave,
How can array of strings be passed as input parameter.for example i have following method
[WebMethod]
public void UpdateInfo(int id, string[] names, string otherinfo){
}
and following is the Jquery call
$.ajax({
type: “POST”,
url: pagePath,
contentType: “application/json; charset=utf-8″,
data: { “id”: “1″, “names:['a','b'],”otherinfo”: “abcd”},
dataType: “json”,
success: successFn,
error: errorFn
});
its not working. It works if i don’t pass array of strings. Could you please help?
At that point of complexity, you might want to consider using JSON.stringify to build the JSON string for you.
Thanks a lot!!! Dave. It worked. You are simply great :)
Hi,
I really like your post, it’s very easy to understand.. even with my limited english…
I have a little problem using jQuery Ajax and asmx webservice and I don’t know how to prevent this.
Here’s the scenario.
I have a textbox and a dropdownlist.
When I set a a value to the texbox I call the webservice
(I set a bind on the blur event to the texbox). I fill up the dropdownlist when I the success event is reached
Everything works at this time
But sometimes, when the webservice is running and I set a new value to the textbox, I can have twice the items in the dropdownlist..
I would like to know how can I abort a ajax request when the same webservice is called?
Any help ?
Thanks.
Steph
I’d suggest one of two things. Either:
1. Make sure the DropDownList’s items are replaced with what comes back from your service, not appended.
2. In your blur event handler, use setTimeout to delay calling the service for 500ms or so. In that same handler, clear the timer before setting it, so that subsequent blur events within that interval will extend the window until activity has stopped.
Hi Dave,
I thank you for your recommandations.
For the first part, yes I did that.
I’ll try your suggestion.
Do you think it should be possible to use the abort method of the jQuery.Ajax ?
I haven’t had much luck canceling rapid/short AJAX calls like that. It works fairly well, but silently fails often enough that I don’t trust it.
Thanks a lot, as a jQuery beginner, im sure this will save me plenty of time on future potential error.
@Alek Davis (4:30 pm – July 16, 2009), thanks for the tidbit on encoding apostrophes. I hadn’t been able to figure out the syntax and once I saw your comment, it made perfect sense. I had initially done:
I forgot that the \’ is going to be escaped and I’d lose my \ on the data passed over the wire.
@Dave Ward – thank you so much! I would have spent a long time trying to figure this stuff out and in a matter of a couple of hours last night, I was able to implement JQuery UI AutoComplete with a ASMX method:
With a to-be-coded server method:
Thank you!
Many thanks!
Hi,
i am using async tree view with AS/VBScript/js
my problem is it compltely hangs the system when i open it for second time.otherwise its running fine….
would you please let me know how to imlement the jquery async tree view with ASP vbscript.
i think my problem is in the source.asp file
thanks in advance
regards,
mitul
Hi,
How can i get the value of selected item.
ex. name with id
textbox.text1 = lord
textbox.text2 = 1
Very good information. Saved my life.
$.ajax({
type: “POST”,
url: “WebService.asmx/WebMethodName”,
beforeSend: function(xhr) {
xhr.setRequestHeader(“Content-type”,
“application/json; charset=utf-8″);
},
dataType: “json”
});
Helpful
ฺBore IE
thank a lot
Hi Dave,
I thank you for your recommandations.
For the first part, yes I did that.
I’ll try your suggestion.
Do you think it should be possible to use the abort method of the jQuery.Ajax ?
This code run only when this json code implement in same website any page. means code runs inside the website page.
i want to run web service through remotely. i created a webservice and i send link to my web service and use any one. please help asap
I am successfully able to call my WCF servive when debuging my application opened on file system. I am updating database in AJAX enabled WCF service which takes two paramaters. But when i post my application on IIS, it does not update my database nor does it give any error. Pls help. the code to call service is below
function Update() { var data = { EmpID: $("#EmpID").val(), ModeStart: $("#ModeStart").val() }; data = JSON.stringify(data); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Service.svc/DoWork", data: data, dataType: "json", success: insertCallback }); }here EmpID and ModeStart are two input fields from where i am taking value as parameters.
Please reply thry mail. I am badly stuck. I dont know much about WCF services and JQuerry. I used the code from a website
Your posts are always of great use and help to me. Thanks bro. Though I’m pretty fast and efficient in using jQuery’s Ajax, I still learn a lot from your posts.
First and foremost, there is no such thing as a “read-only” POST !
First read the HTTP spec, before you start using it, and telling everyone how to use it, before you know it yourself.
POSTs, must be used ONLY, when you want to “change the status of the world”, i.e. you want to change the data that is kept in your server (your own private world).
For “Read-Only” requests you should always use a GET request.
Using POST for anything else, provoques a nasty popup message, if you press “back” or “refresh” the page.
There is also a recomendation from W3C, which defines that every POST should have an HTTP REDIRECT as reply, to avoid the nasty problem mentioned above.
This makes perfect sense, since, after you “change the world”, the page you will return next will be a simple retrieval of the “current status of the world”.
Hence return a REDIRECT, which will tell the browser to do a GET request on the redirect URL, which will be a correct retrieval of he “current status ofthe world”.
And best of all, you can press “back” or “refresh” the page, without any problems.
Try it!
Second, read the jquery.ajax documentation http://api.jquery.com/jQuery.ajax/
and learn that “dataType”, is only used to defined how the response to the request wil be interpreted, it doesn’t affect the way the server interprets the request in any way.
Finally don’t blog about stuff you assume you know … you will misslead many web coders, and convert them to trial an errorcoders, like yourself.
I wouldn’t normally respond to something like this, but I don’t want your comment to scare any future readers away from the correct way to interact with ASP.NET’s JSON services. I’m not sure what brought you here or what motivated this comment, but I assume that you haven’t worked with ASP.NET’s ASMX ScriptServices and ASPX page methods? Using POST is necessary when working with those services, even for requests with no data/body/content (i.e. “read-only” requests). Failure to do so will result in an XML response from ScriptServices and the entire page’s HTML coming back (instead of JSON) with page methods.
I don’t disagree with you in theory about using GET for idempotent requests, but I don’t work at Microsoft and can’t rewrite their framework to handle those requests differently. So, I’m still not sure why you chose to place this comment here.
Given the choice between being stuck with XML and using POST to coax JSON out of the services, I’ll opt for the pragmatic approach every time.
This post only deals with AJAX requests and callbacks. Talking about browser navigation and HTTP redirects is unrelated.
The responses are always JSON in both cases, hence the
dataType. That is correct (though unnecessary when using later versions of jQuery than this post was written about, since jQuery now respects the response’s Content-Type header.).Hi Dave, thank you for your feedback.
My post was triggered by your following words:
” … claim that we’re all amateurs, learning together …”
“… I’ll suggest what I now believe to be a best practice usage …”
There are too many misguided tutorials on the web, which makes junior web programmers loose huge ammounts of time, trying stuff that they do not understand, or have been “tricked” to learn wrong.
This is a huge loss of productivity world wide.
And No, I haven’t worked with ASP.NET’s ASMX ScriptServices and ASPX page methods.
Using POST, is at minimum a POOR choice in terms of security or anything else related with server/client side scrippting.
The link you provide fails to justify such a requirement, but I do understand your concern, but there probably is a way to configure the services to accept GET request for JSON, even forthe code that is provided by Microsoft.
My post, could be too harsh and I’m sorry if it is, but after so many pages wih misleading content, maybe I vented some steam, un-intencionally.
Unfortunatly I don’t seem to be able to edit it, to tone it down.
However, your article should clearly state why you use a POST, for a read-only operation (if really there is no way to use GET for idempotent operations like, reads).
One again ,thank you for your feeback.
Hi Rui Martins.
First and foremost, there is no such thing as a “cool” DOUCHEBAG!
First read the HOW TO BE POLITE ON THE INTERNET spec (http://goo.gl/A44Pc), before you start commenting on blogs, and telling everyone how to use it, before you know it yourself.
COMMENTSs, must be used ONLY, when you want to “change the status of the world”, i.e. you want to people to read what you say without thinking you’re a douchebag (otherwise keep your comments to yourself).
…i think i’ve mocked you enough by now.
Not wanting to spoil Dave article comments, I have to say that, it’s kid like behaviour like yours Rush, that breaks the web as an useful information medium.
You haven’t presented a single item of useful information to the problem in question with your reply.
Didn’t like my reply ? Deal with it.
Look at Dave reply, he showed some prefessionalism in his reply.
Now you can go call your buddies to back you up, and keep behaving like a kid.
Best regards
Rui — please stop now. You have rudely and pompously posted opinions that are demonstrably incorrect, in an area where you admit you don’t have experience. You’ve been called out on it, and you respond by saying there must be a way to configure ASP.Net to make you right. No, you are wrong, and being insistent isn’t going to make you right. Neither is blaming the rest of the Internet for your own rudeness and then turning around and criticizing other people’s web etiquette. If you can’t tone yourself down, please go post on reddit instead of cluttering up technical blogs.
Dave — great articles! I’ve been developing software for over 30 years and have always felt that I’m a constant amateur in a field that changes faster than I can keep up. My latest area of interest is using jQuery and AJAX with ASP.Net, and I’ve gotten a lot of benefit out of reading your blog. When people take things they’ve learned the hard way and write them up in a clear, practical way that gets right to the point, it makes the dry documentation so much easier to comprehend. Thanks for putting your time and effort into this stuff!
Found this somewhere on the net, you can use the jqeury get method to get some stuuf from a page.
getProductById.aspx is my product page (whitout a masterpage etc).
myproductname is my label where i want the mame of the product :)
$.get(“getProductById.aspx”, { ID: “1″ }, function(response) {
$(“#myproductname”).html(response);
});
In the Page_Load you can do a response.write and that will be return in the function. For example if you do response.write(“machine”) in the page load of getProductById.aspx my label will be updated with the text “machine”.
Tested it, and it works fine, but I dont know of any disadvantages…
The disadvantage is that your requests to that ASPX page will run through the entire ASP.NET WebForms page life cycle, even though you don’t need any of that overhead. It’s an approach you’ll see in the PHP world, because requests to PHP files don’t have the inherent overhead that WebForms does. One exception is that if you use a static method marked with the
[WebMethod]attribute, requests to it circumvent the WebForms overhead.Otherwise, it’s best to use an ASMX service for this if you like the built-in JSON [de]serialization feature, or you can just use an HttpHandler (e.g. ASHX) if you want to work with the raw HTTP request and response.
Hi,
I read this article on get the json from the web services, though useful but don’t why it cannot work for me.
Actually, I wrote a asp.net web service as back end and it will return json object to the front end which are purely html5 embeded with ember.js framework.
I tried to put the below code inside my head.
and in my html body,I have the following code which calls this method:
I already put all the html and the ws project inside the same folder,but still cannot work,any ideas on how to connect the web service method from html user interaction?
Kindly give advice!
Thanks
It’s hard to tell what’s wrong without seeing the HTML (be sure to wrap that in <pre lang=”html”> tags if you try posting it again, so that WordPress doesn’t filter it out). One thing I see is that you shouldn’t need to manually run
$.parseJSON(). jQuery will do that for you automatically. Just this should work:Hi Dave,
Thanks for your reply and sorry for my late reply on your comment.
You’re right that it’s hard to tell what’s wrong without seeing html, while the case for me is that why it cannot work correctly is that the html web site is not put inside the same domain or the input parameter should match all web service declared.
I also wonder whether you have any demos or examples which will add microsoft lync feature inside. The main function is that it can check whether the specified LAN ID is online or not. since you’re so familiar with asp.net, can give some suggestions or some demos? I’m really blur in this part,haha, of course that I know I need to read the lync sdk.
Yours
Susan