Tags: , , | Posted by Kevin Babcock on 6/26/2009 12:21 AM | Comments (20)

I’m a big fan of jQuery. I’m no expert, but with a copy of jQuery in Action on my desk and Google Bing at my fingertips I can do a lot of cool things with it. One of the ways I often see people using jQuery is to make Ajax requests. jQuery provides a great library which should take care of just about all your Ajax needs, if you are an UpdatePanel-free web developer. I’ve blogged about it to a small degree, but for more in-depth details you can read about it here. For a quick example, here’s how you might make an Ajax call using jQuery:

$.ajax({
    url: "Services/Customers.svc",
    type: "GET",
    cache: false,
    success: getCustomersCompleteHandler
});

What amazes me is when I see folks using jQuery when all they need is Ajax functionality. If you’re using ASP.NET, you shouldn’t be surprised to know that it’s already provided for you in the client-side library. When you add service references to your ScriptManager, the JavaScript proxies it generates aren’t magic code; they make explicit calls into the ASP.NET AJAX library to perform service calls. You can too!

Using the WebRequest class, making Ajax calls is just as easy with ASP.NET AJAX:

function getCustomers(startIndex, rowCount) {
    var request = new Sys.Net.WebRequest();
    var url = String.format("Services/Customers.svc/?i={0}&c={1}", startIndex, rowCount);
    request.set_url(url);
    request.set_httpVerb("GET");
    request.add_completed(getCustomersCompleted);
    request.invoke();
}

Upon completion of the request you can access returned data or handle timeouts and aborted requests through the WebRequestExecutor object that is passed to the event handler.

function getCustomersCompleted(executor, args) {
    if (executor.get_responseAvailable()) {
        var data = executor.get_responseData();
        var jsonData = eval("(" + data + ")");
        loadContent(jsonData);
    }
    else if (executor.get_timedOut()) {
        // handle request timeout
    }
    else if (executor.get_aborted()) {
        // handle aborted request
    }
}

I built a very simple client-side “grid” that offers paging functionality and retrieves all its data from a web service. You can see that each request made from the ASP.NET AJAX library invokes the web service and returns only the minimum amount of data necessary to update the grid.

Examining a web service request in Internet Explorer Web Development Helper

Examining a web service response in Internet Explorer Web Development Helper

Download the [SOURCE CODE] to see it in action.

If you’re already using jQuery to add other rich functionality to your site then it makes sense to use it for your Ajax needs as well. But if all you need is Ajax, don’t forget that the ASP.NET AJAX library offers the same functionality without the need to manage yet another client-side library in your web app. It’s good to have options.

kick it on DotNetKicks.com

Comments

Joe Chung on 9/23/2009 11:04 PM jQuery is less bulky if all you want to do is Ajax via client-side script.

Where Microsoft ASP.NET Ajax really shines is if you decide to leverage ASP.NET Web services or WCF with Ajax. Then the ScriptManager generates proxy scripts and JSON object models that mimick your server-side object models, encapsulating all the code you wrote above.
Raj on 9/23/2009 11:52 PM Hai,

Nice work.

Please let me know once the source code and demo starts works.
Stilgar on 9/24/2009 4:01 AM The way you've given the examples it seems that it is much easier to do an AJAX request with JQuery which is not true. Most people won't even look that the ASP.NET AJAX code does more things than the JQuery example but even if they do JQuery still seems fine.

You really need to give examples where ASP.NET AJAX beats JQuery (which is 90% of the cases in my opinion). As Joe Chung mentions in the previous post there are the WCF services which generate their own proxy and all you need is call method on an object. Also worth mentioning are the Page Methods which also generate their own proxy. Without these features ASP.NET AJAX does not have any advantages over JQuery (in terms of AJAX calls) but with them it really shines.
Achutha Krishnan on 9/24/2009 5:17 AM Nice explanation. But unable to view or download the demo.
Hamid on 9/24/2009 7:00 AM
Live demo does not work error in the application and also note the download  source code is also not availabe
Pk on 9/24/2009 9:56 AM Ha ha,
Demo link broken !!!
Ajax rulz !!!
Krunal on 9/24/2009 10:04 AM Runtime error is coming in live demo.

Good Job
Krunal
Alex on 9/24/2009 10:47 AM The website for the demo and download is down.

I'd like to see ur code. Regards
Kevin Babcock on 9/24/2009 11:45 AM @Stilgar: Thanks for your comments. I mentioned the generated proxy code in passing in the post, but didn't go into more detail because the aim was simply to point out that making Ajax requests is possible in the ASP.NET AJAX client framework as well. I've talked to several jQuery enthusiasts who simply didn't realize that this was the case.

Using the ScriptManager to generate proxies is probably the simplest method. However, the generated script is quite verbose. And often the script is injected right on the page, meaning no client-side caching and larger page sizes.
Kevin Babcock on 9/24/2009 11:47 AM All,

Thanks for letting me know about the broken links. I've had some trouble lately with my hosting provider and am in the process of migrating to a new hoster. The demo link is working again. I should have the downloadable source code and everything else migrated by this weekend.

--Kevin
Hamid on 9/24/2009 10:17 PM Live demo is availabe but the downloadable source code link does not work
Magnus Bertilsson on 9/25/2009 5:35 AM Yeah but where are Microsofts javascript elegance and why should you use ms ajax in the first place. Why don't Microsoft build a jQuery plugin for the wcf and we can all use one good libary. There is a reason for why Microsofts supports jQuery they can't build selector methods for shit.
Steve Kaschimer on 9/25/2009 9:03 AM Hi Kevin

According to the ASP.NET AJAX site, the jQuery library comes bundled with the ASP.NET AJAX framework (and is also now a standard part of ASP.NET MVC apps)... so really you could choose your poison.

Now, if your not working on and ASP.NET site, your choices are really limited...

I like your examples. Very easy to read and understand. Thanks for taking the times to post this.
Kevin Babcock on 9/25/2009 10:21 AM The source code link is now working. Enjoy!
Janko on 9/25/2009 11:08 AM Nice article, Kevin.

I see that many developers prefer one library over the other (even hate the other) but it's the worse possible way to look at the things. Tools are here to help us solve problems. It would be good to choose tool depending on specific case instead of locking up with only one tool.
Cyril Gupta on 9/26/2009 12:34 AM Have you had a look at how much data ASP.Net Ajax adds to your webpage? Fire up firebug and compare with JQuery. I've used the Scriptmanager ServiceRefrence in the past and I think it's a really bad idea if you can handle JQuery because JQuery will lessen the load time of the page as it's not as bulky as Scriptmanager.

Additionally the code you've listed to call the webservice is actually much harder than it really is. If you have a service Reference on the page, you just need to call the method off it as if it was a Static method and the Service was a Javascript object.

It's awfully simple, yet JQuery should be the preferred method.
Thanigainathan on 9/29/2009 11:54 AM Hi There,

I think combination of both will work out a great. We should not be missing many good features of jquery.

Thanks,
Thani
rehman on 10/21/2009 1:02 AM Hi Kevin
nice article, i downloaded your code,it is working
fine ,the problem when i tried to do same in my project i get so many error
like "Endpoints using 'UriTemplate' cannot be used with  System.ServiceModel.Description.WebScriptEnablingBehavior'"
rehman on 10/21/2009 6:00 AM HOW TO CALL, WHEN  MULTIPLE METHODS IN ONE PAGE
christianArg on 11/4/2009 6:02 AM You can also use a add a ServiceReference in the ScriptManager.

This way you can call the  webService in javascript using the namespace.serviceName.

For example:

function doAjax(){
     MyNameSpace.MyService.MyMethod(arguments, callbacks...)
}


www.asp.net/.../...gWebServicesToAJAXTutorial.aspx