Calling ASP.NET Web Service Using Jquery - Part II - Passing Parameters

5. March 2010 18:35

ASP.NET Jquery  24 Comments

In my previous post I have shown with a simple example on how you call an ASP.NET web service using JQuery. In this post I will show how you on how can you pass parameters to the web method and get the result using the web service.
If you have read my previous post, you have seen that we have just called a web method which returns a simple string back to us. In this example, instead of returning a plain simple string back to the client, we will ask the user to enter two numbers and the call the web service which in turn add the two numbers and returns the result back to the client.

First start up with the design of the page. As we are going to add two numbers, we will add a label, textboxes and a button as shown in the below screenshot:

Add a web service to your project as I have described in my previous post. Follow the same steps to add a web service to your project. The only change that you have to make is to add a method which accepts two numbers as parameters and return the sum of the two numbers. For your convenience, the method is as follows.

[WebMethod]
public int Add(int num1, int num2)
{
	return num1 + num2;
}

The script which I am using here to call the web service is the same as I have shown in my previous post, but the data parameter in the ajax function needs to be changed. When we are calling a web service which returns a normal string to us we can set the data parameter to blank. But this is not the case when we have to pass parameters to the web service to return the result. The data parameter in the Jquery ajax script goes something like this:

data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + ("#txt_num2").val() + "}"

In this parameter the ‘num1’ and ‘num2’ are the name of the parameters in the web service which we have to fulfill if we want the result from the web service. The parameter variable name should always remains the same as defined in the web service method. The parameters and their values are separated by a ‘:’( colon) and a ‘,’ (comma) is used to separate the parameters. The Jquery script $(“txt_num1”).val() will set the value to the parameter and then pass it to the web service method to get the result.

The code for Jquery script to call a web service in this example goes like this:

function CallService() {
            $("#lblResult").addClass("loading");
            $("#lblResult").html('');
            $.ajax({
                type: "POST",
                url: "Service.asmx/Add",
                data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + $("#txt_num2").val() + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnError
            });

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

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

            }
        }

I have added a bit of CSS to show ajax loading style animation. I am not covering it here but sure I will in the later Jquery posts. In my next post I will cover on how to fetch data from the SQL Server using a web service.

Download: JqueryAjaxParams.zip (94.76 kb)

Currently rated 4.8 by 12 people

Comments (24)

Ramon silva Ramon silva
4/16/2010 2:56:52 AM #

Thank you. Your post was very helpful to me

Okesh Okesh
7/12/2011 3:52:42 PM #

Thanks your part 1 and this post was really helpful.

SandeepK SandeepK
10/14/2011 5:24:00 PM #

syntax error: this line is wrong: data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + $("#txt_num2").val() + "}", it should be: data: "{num1:'" + $("#txt_num1").val() + "',num2: '" + $("#txt_num2").val() + "'}",

prashant prashant
10/14/2011 9:01:23 PM #

It is not an error. Have you checked the uploaded source code? If you got the above (the one you postes) working then it might be the version of the jquery that makes the difference. Let me know if this is the case!!

Brad Brad
10/20/2011 2:20:56 AM #

very helpful, thanks!

kshitij kshitij
11/9/2011 12:14:21 AM #

its taking on numbers. i m passing string , it says , internal server error

prashant prashant
11/9/2011 9:46:26 AM #

How you are passing the parameters and what is the return type of the web method? If you are using the above code and calling [b]Add[/b] method while passing strings as a parameter then there would be an error because the Add method will return the sum of two numbers and not strings. If you want to pass the string then change the return type of the method and also the parameters to type string.

Didi Didi
12/1/2011 3:54:44 AM #

How about if the method has no return it just takes an int param and do update on database? the code here doesn't seem to work, what changes should i make?

Prashant Prashant
12/1/2011 10:19:02 AM #

You need to change the Web Method in the service. Make the return type as void and write the update or delete statements as per your requirement. If you are getting some errors let me know.

Moien Moien
1/18/2012 7:15:11 PM #

i am dowload your project it is very good sample for basic developers . tanx for article

manish manish
1/23/2012 11:28:14 AM #

nice explanation

samir samir
2/2/2012 12:02:38 AM #

service is not get called on button click as per the part-I post i have created a asp.net web application then copied code to default.aspx as provided in you page including button and label creation and also added onclientclick for button. also added javaScript provided under head tag. added a new webservice.asmx and tried to call Helloworld method of service by button click but its not working.. pls suggest !!!

Prashant Prashant
2/2/2012 11:18:29 AM #

How you are getting the client ID of the asp button? In my examples I have used normal HTML button and the used the ID in the jQuery (as you can see above). But if you are using the server side button then you have to get the client ID and then use it in the jQuery. Let me know of there is any other problem you are facing!

Dhiraj Dhiraj
3/29/2012 11:18:56 AM #

How to pass an complex object instead of just two parameters. Suppose we create a class in c# which has 10 fields i can't use the Add method with 10 parameters. I have created an entity class with those fields. I want the Add method to accept just one paramater of that class type.

Avadhesh Maurya Avadhesh Maurya
4/4/2012 3:40:53 PM #

I have asp page and i want to call this page webmethod using class object ,so how to pass parameter using jquery ajax method please help me.......

Prashant Prashant
4/5/2012 8:42:45 PM #

Are you saying that the web method is on the page?

tamir tamir
8/20/2012 2:07:40 PM #

i am having a problem with passing a string parameter - it shows me Internal Server Error : An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. [InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/PlusMinus'.] System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405897 System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212 System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47 System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193 System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Can you please help me?

Prashant Prashant
8/20/2012 6:17:58 PM #

The exception message clearly shows the problem is in the URL. If you are using a web service then the URL would be the same as shown in the post above like [i]service.asmx/PlusMinus[/i]. If possible please share the URL you are using, so I can see the exact problem.

tamir tamir
8/21/2012 1:53:14 PM #

i was using : $.ajax({ type: "POST", url: "WebService.asmx/PlusMinus", data: "{'string':"+ $("#display").val() + "}" , contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }) but then i found out the solution and it look like that: var data = { 'equation': $("#dispay").val() }; $.ajax({ type: "POST", url: "WebService.asmx/PlusMinus", data: JSON.stringify(data) , contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }) but now i have a new problem - i want to put all the html pages in one folder, the js pages a seperate folder and the web service in another folder inside the website.. how do i call the web service when they are seperated?

tamir tamir
8/21/2012 4:20:24 PM #

i was using : $.ajax({ type: "POST", url: "WebService.asmx/PlusMinus", data: "{'string':" + s + "}" , contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }) and then i found the solution to my problem which looks like that: var data = { 'equation': displayField.val() }; $.ajax({ type: "POST", url: "WebService.asmx/PlusMinus", data: JSON.stringify(data) , contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }) but now i am having a new problem - if i put the html pages, the js pages and the web service in different folders inside the web site the call is not working, how can i fix this?

Prashant Prashant
8/21/2012 10:11:59 PM #

If you now have the web service in a different folder the you need t o change the [i]url[/i] property of the jquery ajax method for example, of you have the web service inside the [b]service[/b] folder then the [i]url[/i] will be: ../service/WebSerivce.asmx/PlusMinus

subha subha
9/7/2012 12:22:39 PM #

service is not get called on button click as per the part-I post i have created a asp.net web application then copied code to default.aspx as provided in you page including button and label creation and also added onclientclick for button. also added javaScript provided under head tag. added a new webservice.asmx and tried to call Helloworld method of service by button click but its not working.. in ur part 1 u have also taken asp button and level...

subha subha
9/7/2012 2:24:57 PM #

dada it shows "internal server error"...... but i thank all the codes sre correct......my code is blow..plz check it and tell me <script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script> <script src="Scripts/jquery-ui-1.8.23.custom.min.js" type="text/javascript"></script> <script type="text/javascript"> function CallService() { $("#result").html(''); $.ajax({ type: "POST", url: "Service.asmx/Sum", data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + $("#txt_num2").val() + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, error: OnError }); function OnSuccess(data, status) { $("#result").html(data.d); } function OnError(request, status, error) { $("#result").html(request.statusText); } } </script> <div> first no <input id="txt_num1" type="text" /> second no <input id="txt_num2" type="text" /> <input id="Submit1" type="submit" value="submit" onclick="CallService(); return false;" /> </div> result <div id="result"></div> pls reply me soon...its urgnt

Yaz Yaz
9/13/2016 6:09:58 PM #

I have a web service Geo code. Which has a class address with member fields city country state etc. So now I have to call web method by passing instance of the class address. So how do I pass the class object as parameter

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs