Calling ASP.NET Web Service Using Jquery - Part I

5. March 2010 01:27

ASP.NET Jquery  21 Comments

Jquery is now one of the most favorite JavaScript frameworks to play around. It offers some more advance feature to the developers and UI designers to accomplish their task easily and more conveniently. Take an example of AJAX and think where you can face the problems when you have to deal with different browsers who support XMLHTTP request and the one who don’t. I remember, I use to initialize the AJAX’s XMLHTTP object keeping in mind what will be my client’s browser. So, on the first go I have to detect the client’s browser and then set the XMLHTTP object and then process requests.
But Jquery gives us a tons of features to be happy and so as with handling data. In Jquery we have not to worry about what will our client’s browser and what will be the request object. Jquery handles all this for us and makes its pretty easy to use.

So start up with creating a new ASP.NET website project.

When you create a new project a new page named Default.aspx is added by default. I am going to use the same page in this example. If you wish you can change the name of the page. Add a button on the page and a label to show text.

Right-Click the project and add choose New Item. Add a new Web Service.

After this add the below code to the web service code behind file. But before you do that there are some things we need to keep in mind. Let’s talk about a normal web service which we are going to consume in a normal way i.e. using the server-side code. But this is not the case I am explaining here. What we are going to do is to consume the web service on the client-side using Jquery.

Now the changes that you have to made in the code-behind file to allow the web service to be consumed by the client-side script is as follows:
First you have to add or un-comment the attribute above of the web service class. This attribute allows the web service to be called from the client-side script (Jquery or other client-side scripts).

[System.Web.Script.Services.ScriptService]

After this you can write your method the same way you use to write with attribute [WebMethod]. I am just writing a simple method which will return a string.

[WebMethod]
Public string Hello()
{
	Return “Welcome to ASP.NET Web Services and Jquery”;
}

We have our web service ready and now we have to write client-side script to consume this webservice. The method in our web service will return only a plain simple string to the client. First I have added a button and a label to the page. On button click I have called the method (Jquery method) which will call the web service. The response of the web service is then shown on the label. On the page from where we are calling the web service, add the following Jquery script to call the web service.

function CallService()
        {
            $.ajax({
                type: "POST",
                url: "Service.asmx/Hello",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnError
            });
        }

        function OnSuccess(data, status) 
        {
            $("#lblResult").html(data.d);
        }

        function OnError(request, status, error)
        {
            $("#lblResult").html(request.statusText);
        }

In the above code I have created a method and named it CallService(). Inside this method there are several parameters that we have to set to call the web service.

  • type: Can be POST or GET. Web Services do not work with "GET" by default, as to prevent cross-site request forgeries. (Thanks Lee Dumond for pointing this out to me)
  • url: Name of the web service. In the above code you can see I have called the web method ‘Hello’ from the web service named ‘Service’. If you are consuming or calling other web service which is not a part of your project or solution then you need to enter the fully qualified name of the web service with method name you are going to call.
  • data: In this example the data will remain empty, as we are only calling a method which return a simple string and don’t accept any parameter. If the method has some parameters then we will pass the parameters. I will explain on passing parameters in my coming posts.
  • contentType: Should remain the same.
  • datatype: Should remain as it is.
  • success: Here I have called the OnSuccess when the call is complete successfully. If you check the OnSuccess method you will see that I have set the returned result from the web service to the label. In the OnSuccess method body you see ‘data.d’. The ‘d’ here is the short form of data.
  • Error: Same as I have done with OnSuccess. If any error occurred while retrieving the data then the OnError method is invoked.

Run the project and see it in action.

In my coming post on calling web service in ASP.NET using Jquery I will show on how to pass parameters to a web service and get the result and on how can we interact with SQL Server to fetch data and lots of other stuff in Jquery and ASP.NET.

Download: JqueryAjaxDemo.zip (87.55 kb)

Currently rated 4.5 by 10 people

Comments (21)

Lee Dumond Lee Dumond
3/5/2010 9:38:27 PM #

In this post you mention that "type: Can be POST or GET", but you should point out that Web Services do not work with "GET" be default, as to prevent cross-site request forgeries.

Prashant Prashant
3/6/2010 1:45:45 AM #

Thanks for pointing out Lee. I have updated the post.

don don
2/23/2012 10:48:24 AM #

sir i cant able to run this via html can u help me

Prashant Prashant
2/23/2012 9:58:51 PM #

What is error that you received while running this from an HTMl page.

David David
3/5/2012 11:55:40 AM #

Hi, I got an error "Internal Server Error", what could be the cause? Thanks. Regards, David

smriti smriti
3/5/2012 12:57:21 PM #

can u pls explain abt t parameters which r passed in OnError function

prashant prashant
3/6/2012 12:35:11 PM #

Did you use the same solution I have provided above? Internal server error likely to be occur when the parameters passed are incorrect (check if you have used single quote marks correctly). There is a problem with different versions of jQuery. Check with the version of jQuery you are using. Let me know if you face nay other problem.

prashant prashant
3/6/2012 12:54:06 PM #

[b]request:[/b] string that calls an error. [b]status:[/b] status code for the request like 404, 200 etc. [b]error:[/b] I have never used it but it more likely the message for the given error.

Shival Shival
4/7/2012 3:51:03 PM #

Hi prashant, Nice work done but i just want to know the meaning of data.d here. function OnSuccess(data, status) { $("#lblResult").html(data.d); } Regards

Prashant Prashant
4/7/2012 9:42:42 PM #

The data returned to us is in JSON format. If you use fiddler then you can see the returned JSON string and the actual data we need is contained in [b]d[/b]. OnSuccess method the result which is in the JSON format is now in [b]data [/b] variable. But the information which is useful for us in inside [b]d[/b] and therefore to access the result we used [b]data.d[/b]

shirin shirin
5/29/2012 12:07:19 AM #

Hi , Thanks for your post, I get this error: "Microsoft JScript runtime error: '$' is undefined" and this part of code is highlighted : $.ajax( { type: "POST" .... would you please help me? Thanks

Prashant Prashant
5/29/2012 10:43:42 AM #

You receive this error, because you haven't added jquery reference on your webpage. On the head of the page add the jQuery.min.js file. This is a minified version of the jquery and you should always use this version in production environment. You can use either add ASP.NET AJAX CDN or Google CDN or your own jquery file in the head section of your page. Your head section should look something like this if you are using ASP.NET CDN. [quote]<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js" type="text/javascript"></script>[/quote] [b]ASP.NET CDN:[/b] http://www.asp.net/ajaxlibrary/cdn.ashx This will solve your problem.

Aakash Aakash
8/14/2012 10:15:05 AM #

Dear Prashant, I tried the above code as you mention but getting error. As you mention above about the different javascripts so I tried with 3 different javascripts but they are giving different errors as below. [b]jquery-1.3.2.js[/b] giving [b]Internal Server Error[/b] [b]jquery_1.5-jquery_ui.min.js[/b] giving [b]error[/b] [b]http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js[/b] giving [b]error [/b] I tried a lot but unable to resolve this. Please help. Thanks and regards, Aakash

Prashant Prashant
8/15/2012 11:57:09 AM #

It's always difficult to tell the exact problem when dealing with javascript. Make sure that the jquery and jquery UI version that you are using are compatible. Also it's hard to tell where is the problem this way. If possible share the code with me and I'll take a look .

Aakash Aakash
8/16/2012 2:14:25 PM #

@Prashant, Thanks for reply. I am using the exact code you provided above & in demo, but still no success. Here is my code (same as yours) [b]HTML[/b] <input type="button" value="button" onclick="CallService()" /> <div id="lblResult"></div> [b]JAVASCRIPT[/b] function CallService() { $.ajax({ type: "POST", url: "http://192.168.1.2:8811/service/WebService.asmx/Hello", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }); } function OnSuccess(data, status) { $("#lblResult").html(data.d); } function OnError(request, status, error) { $("#lblResult").html(request.statusText+" / "+status); } [b]HEAD[/b] <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"; type="text/javascript"></script>

Prashant Prashant
8/16/2012 3:21:53 PM #

The problem is in the URL you are using. You are trying to call a webservice which is on a different server. If the webservice is in the same application then you just need to give the path of the web service like ../service/service/asmx/Hello This is a known problem for people using jQuery as by default jquery does not support cross-domain (AJAX POST) calls.

Aakash Aakash
8/16/2012 5:33:05 PM #

My application is hosted on local iis & webservice is in the same application. I does as you mention above and now its working fine. Thanks a lot mate. You make my day.

Aakash Aakash
8/16/2012 5:48:04 PM #

One more thing. Isn't there any way to call the webservice on different server. I am working on an android application, in which I am adding html pages in android application & trying to call webservice. I have to call the webservice remotely.

Prashant Prashant
8/16/2012 8:47:20 PM #

Calling a web service and posting data to a web service are different things. You can get the data but posting it to a web service might not work. You can try this but I am not sure that it will work perfectly fine.

Aakash Aakash
8/17/2012 10:14:36 AM #

Thanks bro, Its working now.

vijay vijay
12/13/2014 4:34:46 AM #

Hi All, Is there any solution to call basic aspnet webservice located on remote machine by using only html and jquery for creating android app.

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs