Consuming ASP.NET Web Service through jQuery


Introduction: Here we will discuss jQuery and call a web service through jQuery. As we know, jQuery is a light weight process to write JavaScript code. It's usually a JavaScript Library having cross browser compatibility which is designed to use client side scripting. It is really great to simplify the JavaScript programming and it is also easy to learn. It is basically depend upon the concept of "write less, do more." Now, we are going to see that how to call a web service using jQuery, but first we have to make teh web service.

Let's start the application project to make a web service.

Step 1: Firstly we have to create a web Application

  • Go to Visual Studio 2010
  • Crete the web Application
  • Click OK.
Web site appli8cation

Step 2: Now we have to add a web service named as web service1.

  • Now Go to web application project
  • Right Click on the project
  • Add new Item
  • Choose the Web Service
  • Click OK.
Add New Web Form

Step 3: If we want to write a method which will invoke at the server then we have to make it as [WebMethod] by using it you can access your method on web. Let's have look how it will appear and also look at the code of the  webservice1.asmx.cs file.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebApplication5
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string say(string s)
        {
            return "Welcome  " + s;
        }
    }
}

Code Description: Here we are going to describe the code given above; it's the code for web service if we want to call the web service through script and ASP.NET ajax then we have to add the [System.Web.Script.Services.ScriptService]. Now we are making a web method name as say in which we are passing an argument name as string s and it will return the name of string by adding welcome to it. It is the method that we are going to invoke with the jQuery Script.

Step 4: Now we have to add a web page named as webservicecalling1.aspx.

  • To add a web page go to the project.

  • And right click on it

  • Add a web page

Step 5: If we want to add a jQuery to our project to use it's method then we have to write the code to the source file of webservicecalling1.aspx.

Code:

<%@ Import Namespace="System.Web.Services" %>
<script type="text/javascript"  src="..\Scripts\jquery-1.4.1.min.js"></script>

Description: First of all we have to add a namespace to the file at the top of the .aspx source file. As we know that JavaScript always write in the head section that is the line which we have to add to use it's method defined in the jQuery. Here src have the path of jQuery at which it is placed it must be included in your project if you are using 2010 then it have already included in your web application or you are using lower version than it then you have to add the jQuery to his project for it you will have to download it from the site.

Step 6: Now You have to write the code of the jQuery script

Code :
<script type="text/javascript">
  $(document).ready(function () {
     $("#sayWelcome").click(function (event) {
        $.ajax({
            type: "POST",
            url: "Webservice1.asmx/say",
            data: "{'s': '" + $('#s').val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg)
            {
               Successfullcalling(msg);
            },
            error: Failurecalling
        });
    });
});
function Successfullcalling(res)
 {
   alert(res.d);
 }
function Failurecalling(res)
 {
   alert(res.status + ' ' + res.statusText);
 } 
</script> 

Code Description: Here we will discuss about the jQuery methods. First of all we will also write that code on head section of the web page. Further we are using $(document.ready(function(), If you want an event to work on your page, you should call it inside the ready() function. To Consume a Web Service we have to use a jQuery Command name as .Ajax in which we are passing the type of calling service and giving the url of service and the content Type and also giving the data type will be "json". and also defined further two function name as AjaxSucceded and AjaxFailed and also have the error msg which show an error if there is any problem to invoke the web service.

Step 7: Here is the total code for the whole source file of webservicecalling1.aspx

Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Wesservicecalling1.aspx.cs" Inherits="WebApplication5.Wesservicecalling1" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<
head id="Head1" runat="server">
<title>ASP.NET Web Services</title>
 <script type="text/javascript"  src="..\Scripts\jquery-1.4.1.min.js">  
</script>
 <script type="text/javascript">
   $(document).ready(function () {
       $("#sayWelcome").click(function (event) {
           $.ajax({
               type: "POST",
               url: "Webservice1.asmx/say",
               data: "{'s': '" + $('#s').val() + "'}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (msg) {
                   Successfulcalling(msg);
               },
               error: Failurecalling
           });
       });
   });
   function Successfulcalling(res)
   {
       alert(res.d);
   }
   function Failurecalling(res)
   {
       alert(res.status + ' ' + res.statusText);
   } 
  </script> 
</head>
<
body>
<form id="form1" runat="server">
    <h1 style="background-color: #79A626; color: #006666;"> Consuming Web Services with jQuery </h1>
    Enter your name:
    <input id="s" style="background-color: #FF8040" />
    <br />
    <input id="sayWelcome" value="Welcome On Click" type="button" style="background-color: #79A626"  />
</
form
>
</body>
</
html>

Step 7: Here we have to see the design page of the webservicecalling1.aspx see how it look's like.

Design of Application

Step 8: Now you have to run the application by pressing F5

After Run :

Output

Up Next
    Ebook Download
    View all
    Learn
    View all