What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 16911 |  Welcome, Guest!   Register  Login
Home > Articles > jQuery > Consuming web service (WebMethod) from jQuery in ASP.NET

Consuming web service (WebMethod) from jQuery in ASP.NET

1 vote(s)
Rating: 5 out of 5
Article posted by SheoNarayan on 1/14/2011 | Views: 25808 | Category: jQuery | Level: Intermediate | Points: 250 red flag


This article describes the way of calling ASP.NET Web Service (WebMethod) from jQuery.

Introduction

jQuery has become an integral part of web application development now because of its ability to provide flexibility, extensibility, robustness and fast application development. In this article I have describe the way of calling a web service from jQuery. To do this I have designed a web page having a textbox and a button. I have a web service that returns the data entered into the textbox, its preety simple however you can use this to consume your own complicated web services using jQuery as well.

Note: If you are a web developer, you may find my 101+ jQuery How to's ebook useful.

My sample web page looks like below image. Lets proceed with consuming web service in jQuery in 3 simple steps.

Step 1 - Design a web page

Copy-paste below code in the .aspx page. The code between jQuery reference checks for the CDN version of jQuery file and if somehow it has not loaded then write code to load the local jQuery file. After that remaining html codes are to render a textbox, a button.

<!-- START - jQuery Reference -->

<script type="text/javascript" language="Javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js"></script>

<script type='text/javascript'>//<![CDATA[

if (typeof jQuery == 'undefined') {

document.write(unescape("%3Cscript src='/Script/jquery-1.4.1.min.js' type='text/javascript' %3E%3C/script%3E"));

}//]]>

</script>

<!-- END - jQuery Reference -->

 

 

<p style="color:Blue;">Go to ItFunda.Com for jQuery training.</p>

 

Website name: <asp:TextBox ID="txtBoxName" runat="server" ClientIDMode="Static" />

 

<button id="btnAjax">Call web service using $.Ajax</button>

<h3>Result from web service</h3>

<div id="divResult"></div>

 

<script language="javascript" type="text/javascript">

var webServiceUrl = "../MathService.asmx/GetFullName";

$("#btnAjax").click(function () {

var webServiceUrl = "../MathService.asmx/GetFullName";

var name = $("#txtBoxName").val();

$.ajax({

type: "POST",

url: webServiceUrl,

data: "{'name':'"+ name + "'}",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: SuccessCallBack,

error: FailureCallBack

});

});

 

function SuccessCallBack(data) {

alert(data.d);

}

 

function FailureCallBack(data) {

alert(data.staus + " : " + data.statusText);

}

</script>

The code in the Script block first saves the web method url in the variable (The webmethod name is suffixed with the url of the web service). In my case I have a MathService.asmx webservice that has a web method named GetFullName (We shall see the web service code later in this article).

On click of the button, I have called the jQuery ajax method and passed the type, url, data, contentType, and  dataType parameters. The remaining parameters are callback methods that fires on success and if any error occurs in the web service request. On success of the web service request, SuccessCallBack function fires and on error FailureCallBack function fires. Both accepts an argument that is used to retrive the response from the server.

Notice the code inside the SuccessCallBack function, I have used data.d that is very important (.d gives you the actual data returned as response from the server).

Step 2 - Designing web service to be consumed by jQuery

Below is the code snippet of my web service used in this example, notice the bold line as attribute of the MathService class. System.Web.Script.Services.ScriptService attribute is mandatory for your web service to be consumed via client side script. This is applicable either you consume your web service using jQuery or ASP.NET AJAX.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Script.Services;

using System.Collections;

/// <summary>

/// Summary description for MathService

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]

public class MathService : System.Web.Services.WebService {

public MathService () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

 

[WebMethod]

public string GetFullName(string name)

{

return "[Webservice response]\n\nYou have entered : " + name ;

}

}

My WebMethod is preety simple, just receiving the name as parameter and concatenating some text and returning the string.

I have written hundreds of .NET How to's solution (ebook + source code + video) series based on real time project problems, click here to get it.

Step 3 - Run you .aspx page

If you have followed above two steps, you should be ready to run the .aspx page. After running, enter any name of the website and you will see the alert as shown in the picture below.

Conclusion

Hope this simple article on consuming web services using jQuery will be useful. Thanks for reading and keep reading and sharing your knowledge!

This solution is the part of my 101+ How to's jQuery e-book.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: Karthikanbarasan | Posted on: 15 Jan 2011 02:08:04 AM | Points: 25

Hi,

Nice article... is thr any article for the beginners on how to start using jquery so that it will be useful for me

Posted by: SheoNarayan | Posted on: 15 Jan 2011 02:19:09 AM | Points: 25

Hi Karthik,

You can go through the jQuery tutorials I had written long back at http://www.dotnetfunda.com/tutorials/jquery/ or read this article http://www.dotnetfunda.com/articles/article764-getting-friendly-with-jquery-a-beginners-guide--added-auto-toc-generation-.aspx

If you want to spend little money, you can buy my ebook from http://www.itfunda.com/jquery-how-tos-ebook/Show/45
that comes with more than 100 jQuery how to's methods with source code.

Hope this helps.

Posted by: Vinay13mar | Posted on: 15 Oct 2012 06:18:31 AM | Points: 25
Posted by: Dora743 | Posted on: 05 Feb 2013 02:20:35 AM | Points: 25

Thanks man you just saved my day with this

var webServiceUrl = "../MathService.asmx/GetFullName"; I am using var webServiceUrl = "MathService.asmx/GetFullName"; so I am unable to get my result thanks

>> Write Response - Respond to this post and get points
Related Posts

In this section, we will learn how JQuery works in conjunction with CSS

Jquery is a powerful technology that is like javascript.The major difference is for a certain method to write i javascript you have to write more code where as in Jquery the code is less and the execution is more powerful.You can even create animations like Flash.

jQuery is not a language but it is a well written JavaScript code, As quoted on official jQuery website “it is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development“.

In this article, I shall show how to create a simple slideshow using jQuery in web page.

In this article I am going to show a simple tooltip in GridView using jQuery.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/24/2013 12:18:59 AM