How to use JQuery to call a WebService (*.asmx) method?

Category:
ASP.Net
Publishdate:
16.03.2012
Hits:
33959

Introduction

This article will provide a short introduction of using Jquery to call a method from a webservice.

Jquery Ajax to a WebService method

1. Add a WebService to your project. Rightclick on your project "Add -> New Item" and add a new Web Service to the project:

Add Webservice

2. Replace the class definition with this one:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
 [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

	[WebMethod]
	public string TestMethod(String data)
	{
		return data;
	}
}

3. Add a new "Web Form" to the project
Add Webform
and replace the HTML content with
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        function serviceCall() {
            $.ajax({
                type: "POST",
                url: 'WebService1.asmx/TestMethod',
                data: "{'data':'This is static data from the JavaScript file'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#divResult").html(msg.d);
                },
                error: function (e) {
                    $("#divResult").html("WebSerivce unreachable");
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width: 100px; height: 30px; background-color:yellow;" onclick="serviceCall();">Click me</div>
    <div id="divResult" style="margin-top: 20px;"></div>
    </form>
</body>
</html>

4. Run the project, open your web form and click on the yellow div.
(That's all you need to do if you are using .net 4.0 (in previous versions you may need to add a ScriptHandler to your web.config)  and no IIS 7.5 Urlrewriting module (see the warning at the end of the article)).
The result will be:

Result 1


 

Jquery Ajax to a WebService method with parametes from a TextBox

So far we only used static content in the JavaScript file, which is not very useful.
Let's add a TextBox to our html:

<asp:TextBox ID="txtInput" runat="server" />

Because the TextBox has the runat="server" attribute, the id of the TextBox usually starts with a longer prefix. To address that, we use JQuery to get a reference to the TextBox.
To add a little more complexity, let's also assume that the yellow button should only perform the Ajax call, if the TextBox is not empty.

JavaScript:
<script type="text/javascript">
	function serviceCall() {
		var txtInput = $("#<%=txtInput.ClientID%>").val();
		if (txtInput.length > 0) {
			$.ajax({
				type: "POST",
				url: 'WebService1.asmx/TestMethod',
				data: "{'data':'" + txtInput + "'}",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function (msg) {
					$("#divResult").html(msg.d);
				},
				error: function (e) {
					$("#divResult").html("WebSerivce unreachable");
				}
			});
		}
	}
</script>


Result

Jquery call 2

Complete HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        function serviceCall() {
            var txtInput = $("#<%=txtInput.ClientID%>").val();
            if (txtInput.length > 0) {
                $.ajax({
                    type: "POST",
                    url: 'WebService1.asmx/TestMethod',
                    data: "{'data':'" + txtInput + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $("#divResult").html(msg.d);
                    },
                    error: function (e) {
                        $("#divResult").html("WebSerivce unreachable");
                    }
                });
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width: 100px; height: 30px; background-color: yellow;" onclick="serviceCall();">
        Click me</div>
    <asp:TextBox ID="txtInput" runat="server" />
    <div id="divResult" style="margin-top: 20px;">
    </div>
    </form>
</body>
</html>

Warning

If you are using the UrlRewrite 2 Module for IIS 7.5, you need be careful with the LowerCaseRule. In my case, I spend hours trying to figure out, why my method wasn't called. It turned out to be, that I used PascalCase for the naming of my method, but the method was never called because the UrlRewrite Module changed the casing:

<rule name="LowerCaseRule1" stopProcessing="true">
	<match url="[A-Z]" ignoreCase="false" />
	<action type="Redirect" url="{ToLower:{URL}}" />
</rule>
Change these lines into:
<rule name="LowerCaseRule1" stopProcessing="true">
	<match url="[A-Z]" ignoreCase="false" />
	<conditions>
		<add input="{URL}" matchType="Pattern" pattern="^.+\.((axd)|(js)|(xaml)|(asmx))$" ignoreCase="true" negate="true"/>
	</conditions>
	<action type="Redirect" url="{ToLower:{URL}}" />
</rule>
I hope this warning will be indexed by google, that it may later be found by someone else.

Comments:

Reza - 15.06.2014 - 15:58
Very Nice ,really this code is perfect
thank you so much

Hossam - 12.05.2014 - 08:17
Excellent post, very helpful

Abhi - 11.03.2014 - 07:30
this article is very helpful . thanks

Irfan - 10.09.2013 - 08:24
Your article is very much practical and nice. It is having correct syntax as compared to others articles on internet.

Plz share ur articles at irfaniubp@gmail.com

Regards, Irfan Software Engineer (Dot Net)

Tomot - 03.09.2013 - 10:55
@bhawin: My best guess would be, that the specified application pool is .net 2.0 and you are using a .net 4.0 application. Try to verify that the application pool version is at least as high as the specified .net version from your webapplication.

bhawin - 03.09.2013 - 10:52
everytime i do this it shows internal server error, why, even though i use same code in .net 4

Jide - 12.08.2013 - 09:30
@Sharon. Check the name of the web service used in url: 'WebService1.asmx/TestMethod',.
Could it be that your should be
url: 'Service1.asmx/TestMethod', ?

timons - 19.06.2013 - 05:03
thanks!

Pravesh Singh - 04.05.2013 - 17:36
This is a very nice article on "Calling Web Service from JQuery in ASP.NET". I have found another article that's also helpful for developers.

http://www.mindstick.com/Articles/1a4883ba-583c-4216-b45f-a51f9f973aa7/?Calling%20Web%20Service%20from%20JQuery%20in%20ASP%20NET

Jonny Walker - 11.04.2013 - 09:53
Fucking Awesome Dude!!!

chitranjan - 28.02.2013 - 14:33
this is very nice article if you want to get more example then use this link
http://dotnetnukes.blogspot.in/2013/02/aspnet-webservices.html

chan souvannarath - 13.02.2013 - 15:32
Excellent post, I tried WCF and it's trickier asmx type Web Services seem to be friendlier, WCF works for Silverlight projects, for html5 projects this is easier to deal with.

Tomot - 29.01.2013 - 13:55
@Sharon: I can't quite understand what isn't working in your case. If it doesn't work, why does it add the message to html? Are you running your WebApplication on your local IIS or in Cassini?

I'd suggest you create a new ASP.Net 4.0 or 4.5 WebApplication and try if it works there.

Sharon - 29.01.2013 - 05:18
Tried your method. Can't get it to work!
Passes value to ajax correctly.
Can't call web service...tried name all lowercase,
still didn't work!!
Adds message to html.

Advice?

Add a comment (due to recent massive spam, I've decided to only display new comments after a manual spam check):
Name
E-Mail (will not be displayed)  
Text