Search This Blog

Tuesday, February 4, 2014

Using jQuery ajax to call asmx WebService methods

ASP.NET > WebService > jQuery

Using jQuery ajax to call asmx WebService methods

Example:




Code:

WebService1.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace JQuery
{
    ///



    /// Summary description for WebService1
    ///
    [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 GetCode(string name)
        {
            return "Code for " + name + " is " + "1111";
        }
    }
}

HtmlPage1.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 runat="server">
    <title></title>
        <script src="jquery-2.1.0.min.js" type="text/javascript"></script>
</head>

<body>
    <form id="form1" runat="server">
    <div><br />Access Code</div>
    <div id="code"></div>

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "WebService1.asmx/GetCode",
                data: "name=John",
                dataType: "text",
                success: function (data) {
                    $("#code").html(data);
                }
            });
        });
    </script>
    </form>
</body>
</html>