Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Ajax Call from Master Page to webservice (asmx) through JQuery

4.08/5 (8 votes)
5 Nov 2013CPOL 28.1K  
This tip describes the steps to access server side web service (asmx) from master page JavaScript.

Introduction

This tip describes the steps to access server side web service (asmx) from master page JavaScript. This can be helpful in situations when you want to prevent full page postback and need to communicate from client side to server side from master page.

Using the Code

You need to follow the steps given below:

  1. Add webservice (asmx file) that contains the server side function you want to access from jquery:
    C#
    [WebMethod]
        public string HelloWorld(int Variable1, string Variable2)
        {
            return "Hello World";
        }   
  2. Uncomment the line to allow access to webservice from JavaScript:
    C#
    [System.Web.Script.Services.ScriptService]    
  3. Add master page and add the markup after the form tag:
    ASP.NET
    <span id="ArticleContent">
    <h1>Access server side from jquery ajax from master page</h1>
    <label title="Click to access server from javascript" 
    onclick="SetTabSessionValue(12, 'Hello');">
    Click to access server from javascript</label>
    
    </span> 
  4. Add the JavaScript function that is called when you click on the label to master page. Adjust your webservice path and name accordingly (my webservice name is WSAccessMPJquery.asmx). Also adjust the path for jquery min.js.
    JavaScript
    <script src="js/jquery-1.8.3.min.js" 
    type="text/javascript"></script>
    <script>
    function SetTabSessionValue(Variable1, Variable2) {
    
            var param = "{'Variable1':" + JSON.stringify(Variable1) + 
            ",'Variable2':" + JSON.stringify(Variable2) + "}";
    
            $.ajax({
                type: "POST",
                url: "WSAccessMPJquery.asmx/HelloWorld",
                data: param,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: SetTabSessionValueSucceed,
                error: SetTabSessionValueFailed
            });
        }
        function SetTabSessionValueSucceed(result) {
            alert("text from server: "+ result.d);
        }
    
        function SetTabSessionValueFailed() {
            alert('call failed');
        }
    </script>
  5. Add normal aspx page that uses master page and run the solution.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)