How to call an ASP.net WebService (OR WCF Service) using Jquery

After seeing much response to my previous article “How to calls server side code using JavaScript”, I am very much impressed to write this. I would like keep this much simple.

Step 1: Create a new Ajax enabled Website

Step 2: Add a Web Service (common.asmx or .svc file) to it.

Step 3: on Webservice code behind file make sure that add 

<System.Web.Script.Services.ScriptService()>_

Attribute to your class as show in below. This will enable to call your webservice from JavaScript.

 Your Webservice code behind file should look like below. Here we are adding a Web method “SayHello”, which is taking Name as input parameter and returns string as output parameter.

 

<System.Web.Script.Services.ScriptService()> _

Public Class Common

    Inherits System.Web.Services.WebService 

                <WebMethod(True)> _

    Public Function SayHello(ByVal Name As string) AS string

        Return “Hello” + Name

    End Function

End Class

Step 4:  Now on your Default.aspx Add a Textbox and Button (Button1) control

Step 5: Now add a new folder called scripts in your project add new JavaScript file  Common.js

 Step 6: Download Jqery library from http://jquery.com/  add it to your script folder. 

Step 7: Now open your common.js and add the following reference as shown in below

Step 8: add following Jquery function on your common.js file

$(document).ready(function() {

 $(‘[id$=Button1]’).click(function() { 

var serviceurl =  “http://yourservname/common.asmx/SayHello”;

var varName = $(‘[id$=TextBox1]’).text;

var ajaxdata = “{‘Name’:'” + varName + “‘}”;

      $.ajax({

            type: “POST”,

            url: serviceurl,

            data: ajaxdata,

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

            dataType: “json”,

            success: onSucess(response),

            error: onError

        });

        return false;

 });

  }); 

function onSucess(response) {

    alert(response);

function onError() {

    alert(“Error while calling webservice”);

}

Step 9: Now add your common.js  file and Jquery.js file to your default.aspx page and run your application

 Step 10: Enter a name in your text box and click on button.  You will see your javascript calling web service.

Advertisements

One thought on “How to call an ASP.net WebService (OR WCF Service) using Jquery

  1. Hi my family member! I wish to say that this article is amazing, nice written and include almost all vital infos. I would like to peer extra posts like this .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s